Java Reference
In-Depth Information
Bundle bundle = getInstalledBundle(ctx,
"fancyfoods.department.cheese");
try {
bundle.start();
} catch (BundleException e) {
fail(e.toString());
If bundle can't start,
find out why
}
SpecialOffer offer = waitForService(bundle,
SpecialOffer.class);
assertNotNull("The special offer gave a null food.",
offer.getOfferFood());
assertEquals("Wrong food.", "Wensleydale cheese",
offer.getOfferFood().getName());
Get offer
service
}
protected Bundle getInstalledBundle(BundleContext ctx, String name) {
assertNotNull("No bundle context was injected.", ctx);
for (Bundle b : ctx.getBundles()) {
System.out.println("Checking bundle " + b);
if (b.getSymbolicName().equals(name)) {
return b;
}
}
return null;
}
protected <T> T waitForService(Bundle b, Class<T> clazz) {
try {
BundleContext bc = b.getBundleContext();
ServiceTracker st =
new ServiceTracker(bc, clazz.getName(), null);
st.open();
Object service = st.waitForService(30 * 1000);
assertNotNull("No service of the type " + clazz.getName()
+ " was registered.", service);
st.close();
return (T) service;
} catch (Exception e) {
fail("Failed to register services for " +
b.getSymbolicName() + e.getMessage());
return null;
Give service
30 seconds
to appear
}
}
The ServiceTracker
The eagle-eyed among you will have noticed that the test in listing 8.8 uses a Ser-
viceTracker to locate the service. We did mention this briefly in section 6.2.1, but
for a more detailed explanation we suggest that you look at appendix A.
Unlike normal JU nit test methods, Pax Exam test methods can take an optional
BundleContext parameter. You can use it to locate the bundles and services you're try-
ing to test.
 
Search WWH ::




Custom Search