Skip to content

Instantly share code, notes, and snippets.

@gadieichhorn
Created August 8, 2018 12:55
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save gadieichhorn/137aa1ffb38472a6208b83f83046bdcc to your computer and use it in GitHub Desktop.
Save gadieichhorn/137aa1ffb38472a6208b83f83046bdcc to your computer and use it in GitHub Desktop.
import lombok.Builder;
import lombok.Getter;
import lombok.extern.slf4j.Slf4j;
import org.junit.rules.ExternalResource;
import org.osgi.framework.BundleContext;
import org.osgi.util.tracker.ServiceTracker;
import static org.junit.Assert.assertNotNull;
@Slf4j
public class ServiceTrackerRule<T> extends ExternalResource {
private final BundleContext context ;//= FrameworkUtil.getBundle(ServiceTrackerRule.class).getBundleContext();
private ServiceTracker<T, T> serviceTracker;
@Getter
private T service;
private final Class<T> type;
@Builder
public ServiceTrackerRule(BundleContext context, Class<T> type) {
this.context = context;
this.type = type;
}
@Override
protected void before() throws Throwable {
log.info("BEFORE: {}", context);
serviceTracker = new ServiceTracker<T,T>(context, type, null);
serviceTracker.open();
service = serviceTracker.waitForService(1000);
assertNotNull(type + " service not found", service);
}
@Override
protected void after() {
serviceTracker.close();
log.info("AFTER");
}
}
@gadieichhorn
Copy link
Author

gadieichhorn commented Aug 8, 2018

private final BundleContext context = FrameworkUtil.getBundle(MyTestClass.class).getBundleContext();

@Rule
public ServiceTrackerRule<SomeService> service =
    ServiceTrackerRule.<SomeService>builder().context(context).type(SomeService.class).build();

@gadieichhorn
Copy link
Author

gadieichhorn commented Aug 8, 2018

@test

...
service.getService()
...

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment