我正在尝试使用PowerMockito间谍测试一些代码,我正在使用一个方法(getRootTagMap - 见下文)来返回在测试器中构造的值,(使用PowerMockito,因为该方法是私有的。)
但是,它不是返回值,而是始终调用实际方法,而不是返回构造的值。
不确定我做错了什么
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());
}
}
答案 0 :(得分:2)
我不知道你正在使用的PowerMockito版本是什么,但以下场景对我有用:
doReturn(constructReturnValue()).when(messageProcessorSpy).getRootTagMap(any(JsonAppTag.class));
在 spy 对象上调用的方法的调用应该在when
方法返回的实例中调用,而不是像常规的那样在其中调用模拟对象。