ServiceLoader { public Collection<T> createAll(final Object... arguments) { Collection<T> instances = new ArrayList<T>(classes.size()); for (String className : classes) { T instance = createInstance(className, arguments); if (instance != null) { instances.add(instance); } } return instances; } ServiceLoader(final Class<? extends T> service, final Class<?>... argumentTypes); T create(final String name, final Object... arguments); List<T> createList(final String list); Collection<T> createAll(final Object... arguments); String toSimpleClassName(final String name);  }
@Test public void noRegisteredServices() throws Exception { FileSystem.deleteServiceFile(List.class); ServiceLoader<?> loader = new ServiceLoader<>(List.class); assertThat(loader.createAll()).isEmpty(); }
@Test public void getAllServices() { ServiceLoader<?> loader = new ServiceLoader<>(List.class); assertThat(loader.createAll()) .hasSize(2) .hasAtLeastOneElementOfType(ArrayList.class) .hasAtLeastOneElementOfType(LinkedList.class); }
@Test public void emptyLines() throws Exception { FileSystem.createServiceFile(List.class, "", ArrayList.class.getName(), ""); ServiceLoader<?> loader = new ServiceLoader<>(List.class); assertThat(loader.createAll()) .hasSize(1) .hasAtLeastOneElementOfType(ArrayList.class); }
@Test public void comments() throws Exception { FileSystem.createServiceFile(List.class, "#Comment", ArrayList.class.getName()); ServiceLoader<?> loader = new ServiceLoader<>(List.class); assertThat(loader.createAll()) .hasSize(1) .hasAtLeastOneElementOfType(ArrayList.class); }
@Test @PrepareForTest(ServiceLoader.class) public void readingServiceFileFails() throws Exception { whenNew(BufferedReader.class).withAnyArguments().thenThrow(new IOException()); try { ServiceLoader<?> loader = new ServiceLoader<>(List.class); assertThat(loader.createAll()).isEmpty(); assertThat(systemStream.consumeErrorOutput()).contains("ERROR").containsOnlyOnce(SERVICE_PREFIX + List.class.getName()); } finally { ArgumentCaptor<Reader> captor = ArgumentCaptor.forClass(Reader.class); verifyNew(BufferedReader.class).withArguments(captor.capture()); captor.getValue().close(); } }