1

I want to mock private method, which called from my test method, but instead of mocking, PowerMockito invoke toMockMethod, and I get NPE. toMockMethod is in the same class.

@RunWith(PowerMockRunner.class)
public class PaymentServiceImplTest {

    private IPaymentService paymentService;

    @Before
    public void init() {
        paymentService = PowerMockito.spy(Whitebox.newInstance
                (PaymentServiceImpl.class));
        MockitoAnnotations.initMocks(this);
    }

    @Test
    public void test() throws Exception {
        ...
        PowerMockito.doReturn(mockedReturn)
                .when(paymentService,
                      "toMockMethod",
                      arg1, arg2);
    }
}

Is it normal situation? What a sense to mock method if it has been invoked?

2 Answers2

2

To enable static or non-public mocking with PowerMock for a class, the class should be added to annotation @PrepareForTest. In your case, it should be:

@RunWith(PowerMockRunner.class)
@PrepareForTest(PaymentServiceImpl.class)
public class PaymentServiceImplTest {

    private IPaymentService paymentService;

    @Before
    public void init() {
        paymentService = PowerMockito.spy(Whitebox.newInstance
                (PaymentServiceImpl.class));
        MockitoAnnotations.initMocks(this);
    }

    @Test
    public void test() throws Exception {
        ...
        PowerMockito.doReturn(mockedReturn)
                .when(paymentService,
                      "toMockMethod",
                      arg1, arg2);
    }
}
Artur Zagretdinov
  • 2,034
  • 13
  • 22
0

I'm gonna leave a second answer for my future self here. There's an alternative problem here. If you're calling Static.method make sure "method" is actually defined in Static and not up the hierarchy.

In my case the code called Static.method, but Static extends from StaticParent, and "method" is actually defined in StaticParent.

@RunWith(PowerMockRunner.class)
@PrepareForTest(StaticParent.class)
public class YourTestClass {

    @Before
    public init() {
        PowerMockito.mockStatic(StaticParent.class);
        when(StaticParent.method("")).thenReturn(yourReturnValue);
    }
}

public class ClassYoureTesting {

    public someMethod() {
        Static.method(""); // This returns yourReturnValue
    }
jcvalverde
  • 178
  • 2
  • 6