0

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 );

  }
Neil
  • 14,063
  • 3
  • 30
  • 51
user2201253
  • 125
  • 2
  • 5
  • Where is the error thrown? Please include what you have tried so far to resolve this problem. – slasky Nov 21 '17 at 22:13
  • There is no any error thrown , neither Failure Trace. If I use a BFactory and the code like: B a = mock(B.class); mockStatic(BFactory.class); when(BFactory.getA()).thenRturn(a); then it works fine, but I do not want to add a Factory just for this mock test purpose. – user2201253 Nov 21 '17 at 22:20

1 Answers1

0

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
glytching
  • 44,936
  • 9
  • 114
  • 120