OSGIServiceLoader implements BundleListener { @Override public void bundleChanged(BundleEvent bundleEvent) { Bundle bundle = bundleEvent.getBundle(); if (bundleEvent.getType() == BundleEvent.STARTED) { checkAndLoadBundle(bundle); } else if (bundleEvent.getType() == BundleEvent.STOPPED) { checkAndUnloadBundle(bundle); } } OSGIServiceLoader(BundleContext context); BundleContext getBundleContext(); Set<Bundle> getResourceBundles(); @Override void bundleChanged(BundleEvent bundleEvent);  }
@Test public void testBundleChanged() throws Exception { Set<Bundle> resultBundles; MockBundleContext mockBundleContext = new MockBundleContext(); MockBundle startedBundle = new MockBundle(); startedBundle.setState(Bundle.ACTIVE); startedBundle.setBundleId(1); startedBundle.setBundleContext(mockBundleContext); MockBundle stoppedBundle = new MockBundle(); stoppedBundle.setState(Bundle.INSTALLED); stoppedBundle.setBundleId(2); stoppedBundle.setBundleContext(mockBundleContext); MockBundle flipBundle = new MockBundle(); flipBundle.setState(Bundle.INSTALLED); flipBundle.setBundleId(3); flipBundle.setBundleContext(mockBundleContext); mockBundleContext.installBundle(startedBundle); mockBundleContext.installBundle(stoppedBundle); mockBundleContext.installBundle(flipBundle); mockBundleContext.setServiceCount(0); OSGIServiceLoader instance = new OSGIServiceLoader(mockBundleContext); resultBundles = instance.getResourceBundles(); assertThat(resultBundles).hasSize(1); assertThat(mockBundleContext.getServiceCount()).isEqualTo(2); mockBundleContext.setServiceCount(0); BundleEvent startedEvent = new BundleEvent(BundleEvent.STARTED, flipBundle); instance.bundleChanged(startedEvent); resultBundles = instance.getResourceBundles(); assertThat(resultBundles).hasSize(2); assertThat(mockBundleContext.getServiceCount()).isEqualTo(2); mockBundleContext.setServiceCount(0); BundleEvent stoppedEvent = new BundleEvent(BundleEvent.STOPPED, flipBundle); instance.bundleChanged(stoppedEvent); resultBundles = instance.getResourceBundles(); assertThat(resultBundles).hasSize(1); assertThat(mockBundleContext.getServiceCount()).isEqualTo(0); }