Search code examples
javamockitopowermockmockstatic

PowerMock throw initialzationError when a class's static method return same a same class's object


An initializationError is thrown. I'm using powermock 1.6.4 and javassist-3.20.0. It seems I can't mock and mockstatic on the same class (at the same time).

interface B
{
  public static B getA()
  {
    return new B()
      {
      };
  }
}

a test code is:
@PrepareForTest({B.class})
@Test
  public void testB()
  {
    B a = mock( B.class );
    mockStatic( B.class );
    when( B.getA() ).thenReturn( a );

  }

Solution

  • You have to prepare the B mock (by, for example, using PowerMockRunner) otherwise the test will throw a ClassNotPreparedException at this line:

    mockStatic( B.class );
    

    This test will pass (though since it has no assertions it might be more accurate to say that this test will not throw an exception ;):

    @RunWith(PowerMockRunner.class)
    @PrepareForTest({B.class})
    public class BTest {
    
        @Test
        public void testB() {
            B a = Mockito.mock(B.class);
            PowerMockito.mockStatic(B.class);
            Mockito.when(B.getA()).thenReturn(a);
        }
    }
    

    I have verified this using:

    • Mockito v1.10.19 with PowerMock v1.6.4
    • Mockito v2.7.19 with PowerMock v1.7.0