ListCollectingServiceLoader implements CollectingServiceLoader<S> { @Override public Collection<S> loadServices(Class<S> service) { serviceLoaderWrapper.load(service); Collection<S> services = new ArrayList<>(); for (Iterator<S> iterator = serviceLoaderWrapper.iterator(); iterator.hasNext();) { try { S instance = iterator.next(); services.add(instance); } catch (ServiceConfigurationError serviceConfigurationError) { logger.error("Error while loading implementations of {}", service.getName(), serviceConfigurationError); } } return services; } ListCollectingServiceLoader(); @VisibleForTesting  ListCollectingServiceLoader(ServiceLoaderWrapper<S> serviceLoaderWrapper); @Override Collection<S> loadServices(Class<S> service);  }
@Test public void loadServices_delegatesLoading() { when(serviceLoaderWrapper.iterator()).thenReturn(mock(Iterator.class)); ListCollectingServiceLoader<MetricsPublishingService> collectingServiceLoader = new ListCollectingServiceLoader<>(serviceLoaderWrapper); collectingServiceLoader.loadServices(MetricsPublishingService.class); InOrder inOrder = inOrder(serviceLoaderWrapper); inOrder.verify(serviceLoaderWrapper).load(same(MetricsPublishingService.class)); inOrder.verify(serviceLoaderWrapper).iterator(); }
@Test public void loadServices_returnsLoadedServices() { MetricsPublishingService service1 = mock(MetricsPublishingService.class); MetricsPublishingService service2 = mock(MetricsPublishingService.class); MetricsPublishingService service3 = mock(MetricsPublishingService.class); List<MetricsPublishingService> expectedServices = asList(service1, service2, service3); when(serviceLoaderWrapper.iterator()).thenReturn(expectedServices.iterator()); ListCollectingServiceLoader<MetricsPublishingService> collectingServiceLoader = new ListCollectingServiceLoader<>(serviceLoaderWrapper); Collection<MetricsPublishingService> actualServices = collectingServiceLoader.loadServices(MetricsPublishingService.class); assertThat(actualServices) .containsExactlyInAnyOrder(expectedServices.toArray(new MetricsPublishingService[0])); }
@Test public void loadServices_returnsLoadedServices_whenOneServiceThrows() { MetricsPublishingService service1 = mock(MetricsPublishingService.class); MetricsPublishingService service3 = mock(MetricsPublishingService.class); Iterator<MetricsPublishingService> iterator = mock(Iterator.class); ServiceConfigurationError error = new ServiceConfigurationError("Error message"); when(iterator.hasNext()).thenReturn(true, true, true, false); when(iterator.next()).thenReturn(service1).thenThrow(error).thenReturn(service3); when(serviceLoaderWrapper.iterator()).thenReturn(iterator); ListCollectingServiceLoader<MetricsPublishingService> collectingServiceLoader = new ListCollectingServiceLoader<>(serviceLoaderWrapper); Collection<MetricsPublishingService> actualServices = collectingServiceLoader.loadServices(MetricsPublishingService.class); assertThat(actualServices) .containsExactlyInAnyOrder(service1, service3); }