Java 我告诉PowerMockito spy返回一个值,那么它为什么要调用实际的方法呢?

Java 我告诉PowerMockito spy返回一个值,那么它为什么要调用实际的方法呢?,java,mockito,powermock,Java,Mockito,Powermock,我正在尝试使用PowerMockito spy测试一些代码,我正在存根一个方法(getRootTagMap——见下文)以返回在测试仪中构造的值(使用PowerMockito,因为该方法是私有的) 但是,它总是调用实际的方法,而不是返回构造的值,而不是返回值 不知道我做错了什么 import org.junit.Test; import org.junit.runner.RunWith; import org.powermock.core.classloader.annotations.Prepa

我正在尝试使用PowerMockito spy测试一些代码,我正在存根一个方法(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());
    }
}

我不知道您使用的PowerMockito版本是什么,但以下场景适合我:

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

spy对象上模拟的方法的调用应该在
when
方法返回的实例中调用,而不是像在常规mock对象中那样在其内部调用。

您是否发现了问题所在?我现在也有同样的问题,不知道该怎么办。。