Using PojoSR for unit testing OSGi bundles
So soon after the initial release of the Apache Felix httplite bundle, a sudden fear gripped me: that someone might actually use the bundle and find defects! While writing httplite I’d written informal tests but had nothing proper in place. For many of the tests I needed to execute code in an OSGi context and could not rely on plain old junits. I could have gone down the road of mocking things but, being lazy, I want to do as little as possible
I checked into using a full OSGi framework context via Pax Exam, but found that Java 1.4 (JUnit 3) is not supported. Also the documentation seems a bit overly complex for the “just get it working” user, such as me. I also had written framework launching things in the past but wanted to write/maintain as little as possible and be as maven-like as possible. Karl on the Felix development list suggested I checked out PojoSR.
I opted to use PojoSR and it’s working quite nicely. To add unit tests to an OSGi bundle with PojoSR, you need to:
- Add the PojoSR dependency to your project.
- Write some code that initializes the PojoSR registry and activates your bundle.
For item #1, add this dependency:
Note, if you get an “org.osgi.vendor.framework property not set” error when executing tests, check and see if you have Felix 4.1 or less as a dependency. If so remove it or update to 4.2 to resolve the error.
For #2, I opted to write an Abstract JUnit test case that initialized PojoSR. This probably will not work for adapting existing TestCases but luckily the code necessary is small so it should not be difficult to add to specific test cases as needed.
After making these changes maven and Eclipse were able to execute my tests. Writing new test cases is easy as I simply extend my abstract pojoSR test case and can already know that my bundle is running and access the BundleContext if needed.
While I’m sure there are defects lurking in httplite, at least now I have some baseline tests and the ability to capture problems in tests going forward!