Skip to content

Add support for PowerMockRunner

Compare
Choose a tag to compare
@sbabcoc sbabcoc released this 27 Nov 19:00
· 120 commits to master since this release

This release works around an execution issue that prevented use of PowerMockRunner.

Once activated, PowerMock apparently wants to proxy everything. One side effect of this proclivity is that it can subtly alter objects in obscure parts of the implementation, far removed from any intended code. This can cause anomalous behavior, like the object-type mismatch that occurred deep in the bowels of Apache Commons Configuration.

To avoid the object-type mismatch, I now instantiate the configuration object in the interceptor for the run method, prior to the execution of PowerMockRunner.

These revisions include PowerMock unit tests. The JUnit Foundation library is targeted at Java 7, but Mockito requires Java 8, so I updated the project to compile for Java 7 and execute tests in Java 8. This effort was very useful, because figuring out how to get this to work revealed that I didn't need the maven-toolchain-plugin, the removal of which allowed me to eliminate the Eclipse lifecycle-mapping plugin.

NOTE - The native implementation of PowerMockRunner uses a deprecated JUnit runner model that JUnit Foundation doesn't support. You need to delegate test execution to the standard BlockJUnit4ClassRunner (or subclasses thereof) to enable reporting of test lifecycle events. This is specified via the @PowerMockRunnerDelegate annotation, as shown below:

package com.nordstrom.automation.junit;

import static org.hamcrest.CoreMatchers.equalTo;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.mockito.Mockito.when;
import static org.powermock.api.mockito.PowerMockito.mockStatic;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.BlockJUnit4ClassRunner;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.modules.junit4.PowerMockRunner;
import org.powermock.modules.junit4.PowerMockRunnerDelegate;

@RunWith(PowerMockRunner.class)
@PowerMockRunnerDelegate(BlockJUnit4ClassRunner.class)
@PrepareForTest(PowerMockCases.StaticClass.class)
public class PowerMockCases {
    
    @Test
    public void testHappyPath() {
        mockStatic(StaticClass.class);
        when(StaticClass.staticMethod()).thenReturn("mocked");
        assertThat(StaticClass.staticMethod(), equalTo("mocked"));
    }
    
    static class StaticClass {
        public static String staticMethod() {
            return null;
        }
    }
}