Search code examples
junitaspectjspring-roopowermock

PowerMockito and AspectJ giving me NullPointerException


I have a Class under Test that looks like this:

import org.springframework.roo.addon.javabean.RooJavaBean;
import org.springframework.roo.addon.jpa.activerecord.RooJpaActiveRecord;

@RooJavaBean
@RooJpaActiveRecord(table="test_class", finders={ "findById" })
public class TestClass {
    boolean test;

    public static String returnSomething() {
        return "X";
    }
}

As you can see, it has Roo-Annotations and a static method I need to mock.

My test uses the (mocked) static method and also creates new objects from this class.

import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.powermock.api.mockito.PowerMockito;
import org.powermock.core.classloader.annotations.PowerMockIgnore;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.modules.junit4.PowerMockRunner;

@RunWith(PowerMockRunner.class)
@PrepareForTest(TestClass.class)
@PowerMockIgnore("javax.management.*")
public class PowerMockitoTest {

    @Test
    public void test() {
        PowerMockito.mockStatic(TestClass.class);
        PowerMockito.when(TestClass.returnSomething()).thenReturn("Y");

        Assert.assertEquals("Y", TestClass.returnSomething());

        TestClass x = new TestClass();
    }

}

The call to new TestClass() gives me the following Exception:

java.lang.NullPointerException
    at org.springframework.beans.factory.aspectj.AnnotationBeanConfigurerAspect.ajc$if$bb0(AnnotationBeanConfigurerAspect.aj:1)
    at ....TestClass.<init>(TestClass.java:8)

and when I debug into the AnnotationBeanConfigurerAspect class I can see that the Configurable passed into this method is indeed null

public static final boolean ajc$if$bb0(Configurable c) {
        return c.preConstruction();
    }

Is this a bug in Powermock? Are there any workarounds?

Versions used:

[INFO] +- junit:junit:jar:4.11:test
[INFO] |  \- org.hamcrest:hamcrest-core:jar:1.3:test
[INFO] +- org.mockito:mockito-all:jar:1.9.5:test
[INFO] +- org.powermock:powermock-module-junit4:jar:1.5.3:test
[INFO] |  \- org.powermock:powermock-module-junit4-common:jar:1.5.3:test
[INFO] |     \- org.powermock:powermock-reflect:jar:1.5.3:test
[INFO] +- org.powermock:powermock-api-mockito:jar:1.5.3:test
[INFO] |  \- org.powermock:powermock-api-support:jar:1.5.3:test
[INFO] +- org.powermock:powermock-module-junit4-rule:jar:1.5.1:test
[INFO] |  +- org.powermock:powermock-classloading-base:jar:1.5.1:test
[INFO] |  \- org.powermock:powermock-core:jar:1.5.1:test
[INFO] \- org.powermock:powermock-classloading-xstream:jar:1.5.1:test

Solution

  • I filed a bug and provided a fix: https://github.com/jayway/powermock/issues/676