PowerMock for Integration Testing

A while ago I blogged about how to use the PowerMock Rule to bootstrap PowerMock without using a JUnit runner. A problem that you’ll likely run into sooner or later when using this approach in an integration test is the need to ignore certain classes or packages from being loaded by the PowerMock classloader using the @PowerMockIgnore annotation. This is actually not limited to the Rule but happens when using the standard JUnit runner as well but it’s much more likely to occur in an integration test. Frequent candidates for this are various XML, log, and persistence frameworks . The reason is that some frameworks tries to instantiate classes using reflection and does this from the thread context classloader (PowerMock’s classloader) but then tries to assign the created object to a field not loaded by the same classloader. So by using @PowerMockIgnore you can can instruct PowerMock to defer the loading of a certain package to the parent classloader. What you need to ignore is case specific but usually it’s e.g. the XML framework or some packages that interact with it. E.g. @PowerMockIgnore({"org.xml.*", "javax.xml.*"}).

Example

Let’s say we have a (very stupid) Spring bean like this:

and for demonstration we’d like to mock the static method call to IdGenerator.generateNewId(). Let’s write a simple test bootstrapped by Spring using the classloader version of PowerMockRule:

If you run this test you’ll get the following error:

The reason is that companyRepository.getAllEmployees() implementation called from MyBean bean above parses the employee list using Java’s XML parsing (javax.xml.parsers.DocumentBuilderFactory). Thus we must use the PowerMockIgnore annotation to ignore the framework:

Re-run the test and it’ll now pass.

Introducing PowerMock Java Agent

To make it easier to use PowerMock for integration testing version 1.4.9 introduces yet another way to bootstrap the framework, this time using a java agent. Instead of using classloaders to bootstrap and perform byte-code manipulation we now use Java’s instrumentation API. This means that you won’t run into classloading issues as those presented in the previous example. The test looks exactly the same though:

Even though the test looks exactly the same the internal implementation has a lot of differences. To have a look at the real code behind the to examples have a look in subversion here for the first example and here for the java agent example.

Round-up

Using the Java agent can help you out when you run into hard-to-resolve classloading issues with PowerMock. The implementation is still experimental and we are aware of some bugs and limitations. To know more and find help getting started with the agent please have a look at the documentation.

6 Comments

  1. Minsoo

    Thank you Johan. We could jump this hurdle with your notes. but we add org.w3c.* to PowerMockIgnore in addition to your recommendation.

  2. Deksa

    Hi Johan,

    if I use Spring’s @ContextConfiguration, it gives me
    “when() requires an argument which has to be ‘a method call on a mock’”
    although I have
    @PrepareForTest({Utils.class, Utils2.class})
    and
    PowerMockito.mockStatic(Utils.class);
    PowerMockito.when(Utils.staticMethod()).thenReturn(returnValue);
    PowerMockito.mockStatic(Utils2.class);
    PowerMockito.when(Utils2.staticMethod()).thenReturn(returnValue);

    On the other hand, if I use:
    @RunWith(PowerMockRunner.class)
    the application context xml configuration file is not taken into account (this I expect cause I am not using the spring runner @RunWith(SpringJUnit4ClassRunner.class) )

    It seems to me like it is buggy. Can you see if I am doing something wrong?

    Cheers,
    Deksa

  3. Deksa

    If I place the @Rule field
    I get “java.lang.IllegalStateException: Failed to load ApplicationContext”
    which is caused by
    “java.io.FileNotFoundException: class path resource [springApplicationContext.xml] cannot be opened because it does not exist”

    This is not an issue when I don’t use PowerMock. So I am guessing there is a bug somewhere. Correct me if I am wrong.

    Cheers,
    Deksa

  4. Katharina

    Thank you Johan. Your article allows us to test classes that extend Swing-Components by adding @PowerMockIgnore({“javax.swing.*”}).

  5. Oliver

    Katharina, if you can please provide details how you were able to test classes that extend Swing components? We’re also trying to unit test classes that extend Swing components, and have been unsuccessful in mocking Swing out. Every solution I’ve found is geared towards running the GUI, which is not what we need. Thanks!

  6. Oliver

    I figured it out.

    Swing cannot be mocked out completely. The combination of

    @PowerMockIgnore({ “javax.swing.*” })

    and calling

    UIManager.setLookAndFeel(new MockLookAndFeel());

    allows our unit tests to run. The mock look and feel class is as follows:

    public class MockLookAndFeel extends BasicLookAndFeel {
    @Override
    public String getDescription() {
    return “test”;
    }
    @Override
    public String getID() {
    return “testId”;
    }
    @Override
    public String getName() {
    return “test”;
    }
    @Override
    public boolean isNativeLookAndFeel() {
    return false;
    }
    @Override
    public boolean isSupportedLookAndFeel() {
    return true;
    }
    }

Leave a Reply