我告诉PowerMockito间谍返回一个值,那么为什么调用实际方法呢? [英] I am telling PowerMockito spy to return a value, so why is it calling the actual method?

查看:512
本文介绍了我告诉PowerMockito间谍返回一个值,那么为什么调用实际方法呢?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用PowerMockito间谍测试一些代码,并且对方法(getRootTagMap,请参阅下文)进行存根以返回在测试器中构造的值(使用PowerMockito,因为该方法是private。)

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.

不知道我在做什么错

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());
    }
}


推荐答案

I不知道您使用的PowerMockito版本是什么,但是以下情况对我有用:

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));

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

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.

这篇关于我告诉PowerMockito间谍返回一个值,那么为什么调用实际方法呢?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆