ServiceLoader { public List<T> createList(final String list) { List<T> instances = new ArrayList<T>(); for (String entry : list.split(",")) { entry = entry.trim(); if (!entry.isEmpty()) { T instance; int separator = entry.indexOf(':'); if (separator == -1) { instance = create(entry, (Object) null); } else { String name = entry.substring(0, separator).trim(); String argument = entry.substring(separator + 1).trim(); instance = create(name, argument); } 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 getServicesFromEmptyList() { ServiceLoader<?> loader = new ServiceLoader<>(Throwable.class, String.class); assertThat(loader.createList("")).isEmpty(); }
@Test public void getServicesFromSingletonListWithoutArgument() { ServiceLoader<Throwable> loader = new ServiceLoader<>(Throwable.class, String.class); assertThat(loader.createList(NullPointerException.class.getName())) .hasSize(1) .allSatisfy(element -> assertThat(element).isInstanceOf(NullPointerException.class)) .allSatisfy(element -> assertThat(element).hasMessage(null)); }
@Test public void getServicesFromSingletonListWithArgument() { ServiceLoader<Throwable> loader = new ServiceLoader<>(Throwable.class, String.class); assertThat(loader.createList(NullPointerException.class.getName() + ": Hello World!")) .hasSize(1) .allSatisfy(element -> assertThat(element).isInstanceOf(NullPointerException.class)) .allSatisfy(element -> assertThat(element).hasMessage("Hello World!")); }
@Test public void getServicesFromValidDoubletonList() { ServiceLoader<Throwable> loader = new ServiceLoader<>(Throwable.class, String.class); List<Throwable> exceptions = loader.createList( NullPointerException.class.getName() + ": Hello World!, " + IllegalStateException.class.getName() ); assertThat(exceptions).hasSize(2); assertThat(exceptions.get(0)).isInstanceOf(NullPointerException.class).hasMessage("Hello World!"); assertThat(exceptions.get(1)).isInstanceOf(IllegalStateException.class).hasMessage(null); }
@Test public void getServicesFromInvalidDoubletonList() { ServiceLoader<Throwable> loader = new ServiceLoader<>(Throwable.class, String.class); List<Throwable> exceptions = loader.createList(NullPointerException.class.getName() + ", " + String.class.getName()); assertThat(exceptions) .hasSize(1) .allSatisfy(element -> assertThat(element).isInstanceOf(NullPointerException.class)) .allSatisfy(element -> assertThat(element).hasMessage(null)); assertThat(systemStream.consumeErrorOutput()) .contains("ERROR") .containsOnlyOnce(Throwable.class.getName()) .containsOnlyOnce(String.class.getName()); }