I tell PowerMockito spy to return a value, so why does it call the actual method?

I am trying to test some code using the PowerMockito spy, and I complete the method (getRootTagMap - see below) to return the value constructed in the test (using PowerMockito because the method is private.)

However, instead of returning a value, it always calls the actual method, rather than returning the constructed value.

Not sure what I'm doing wrong

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

import static org.powermock.api.mockito.PowerMockito.spy;


@RunWith(PowerMockRunner.class)
@PrepareForTest({JsonAppMessageProcessor.class})
public class TestPropStoreAppController {
    @Test public void testSaveJsonAppTagChangesToPropStore() throws Exception {
        JsonAppMessageProcessor messageProcessorSpy = spy(new JsonAppMessageProcessor());
        when(messageProcessorSpy, "getRootTagMap", any(JsonAppTag.class)).thenReturn(constructReturnValue());
        // I tried it this way too...
        //  doReturn(constructReturnValue()).when(messageProcessorSpy, "getRootTagMap", any(JsonAppTag.class));
        // the following call calls the real getRootTagMap(JsonAppTag) method instead of returning the stub
        messageProcessorSpy.saveChanges(constructParameterForChanges());
    }
}
+1
source share
1 answer

I don’t know what version of PowerMockito you are using, but the following script works for me:

doReturn(constructReturnValue()).when(messageProcessorSpy).getRootTagMap(any(JsonAppTag.class));

, spy, , when, , mock.

+2

Source: https://habr.com/ru/post/1583802/


All Articles