问题
I am trying to test some code using a PowerMockito spy, and I am stubbing a method (getRootTagMap--see below) to return a value constructed in the tester, (Using PowerMockito, because the method is private .)
However instead of returning the value, it is always invoking the actual method, rather than returning the constructed value.
Not sure what I am 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:
I dont know what is the PowerMockito version you are using, but the following scenario works for me:
doReturn(constructReturnValue()).when(messageProcessorSpy).getRootTagMap(any(JsonAppTag.class));
The call of the method that you are mocking on a spy object should be called in the instance returned by the when
method, and not inside it like in a regular mock object.
来源:https://stackoverflow.com/questions/27827892/i-am-telling-powermockito-spy-to-return-a-value-so-why-is-it-calling-the-actual