Chapter 7. Testing OSGi based Applications

Table of Contents

OSGi Mocks
Integration Testing
Creating a simple OSGi integration test
Installing test prerequisites
Advanced testing framework topics
Creating an OSGi application context
Specifying the OSGi platform to use
Waiting for the test dependencies
Testing framework performance

By following best practices and using the Spring Dynamic Modules support, your bean classes should be easy to unit test as they will have no hard dependencies on OSGi, and the few OSGi APIs that you may interact with (such as BundleContext) are interface-based and easy to mock. Whether you want to do unit testing or integration testing, Spring-DM can ease your task.

OSGi Mocks

Even though most OSGi API are interfaces and creating mocks using a specialized library like EasyMock is fairly simple, in practice the amount of code of setting the code (especially on JDK 1.4) becomes cumbersome. To keep the tests short and concise, Spring-DM provides OSGi mocks under org.springframework.osgi.mock package.

It's up to you to decide whether they are useful or not however, we make extensive use of them inside Spring-DM test suite. Below you can find a code snippet that you are likely to encounter in our code base:

private ServiceReference reference;
private BundleContext bundleContext;
private Object service;
    
protected void setUp() throws Exception {
	reference = new MockServiceReference();
	bundleContext = new MockBundleContext() {

		public ServiceReference getServiceReference(String clazz) {
			return reference;
		}

		public ServiceReference[] getServiceReferences(String clazz, String filter) 
				throws InvalidSyntaxException {
			return new ServiceReference[] { reference };
		}
		
		public Object getService(ServiceReference ref) {
		    if (reference == ref)
		       return service;
		    super.getService(ref);
		}
	};

	...
}
	
public void testComponent() throws Exception {
    OsgiComponent comp = new OsgiComponent(bundleContext);
    
    assertSame(reference, comp.getReference());
    assertSame(object, comp.getTarget());
}

As ending words, experiment with them and choose whatever style or library you feel most confortable with. In our test suite we use the aforementioned mocks, EasyMock library and plenty of integration testing (see below).