I am telling PowerMockito spy to return a value, so why is it calling the actual method?

有些话、适合烂在心里 提交于 2019-12-24 14:31:55

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!