I came across a real unit testing nightmare the other day attempting to write tests for the new SSO system. SiteMinder has it's own SDK and agent API that you can extend, but it's all based on JNI. Even though my code was implemented in pure java, I had to implement an interface (com.netegrity.policyserver.smapi.ActiveExpression) and use a class (com.netegrity.policyserver.smapi.ActiveExpressionContext) that had a static initializer loading a native library.

In prior fights with this situation, I have refactored all behavior out into another class that mirrors the API of the offending class and then simply delegated to my nice new shiny testable class. But I don't like that because it creates more lines of code which are solely for unit testing, and makes the reader of the code say “What's this for?”. In other words, it smells.

After doing some searching, I came across PowerMock . PowerMock allows me to unit test my class as is by suppressing the static initializer. Here's a snippet of my code:

PowerMock isn't perfect. You are forced to run the test with the PowerMock runner instead of the stock Junit runner or even the Spring JUnit runner, but it's benefits definitely outweigh the drawbacks.

I urge you to take a look at PowerMock. It's nice.