如何在不运行方法的情况下模拟方法调用和返回值? [英] How to mock method call and return value without running the method?

查看:143
本文介绍了如何在不运行方法的情况下模拟方法调用和返回值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

考虑以下方法:

public boolean isACertainValue() {
        if(context.getValueA() != null && context.getValueA().toBoolean() == true) {
        if(context.getType() != null && context.getType() == ContextType.certainType) {
            return true;
        }
    }
    return false;
}

我没有写这段代码,它很丑陋,它完全是过于复杂,但我必须使用它。

I did not write this code, it is ugly as hell, it is totally overcomplicated but I have to work with it.

现在我想测试依赖于对此方法的调用的方法。

Now I want to test a method that relies on a call to this method.

我以为我可以通过以下方式解决这个问题:

I thought I could deal with this by:

Mockito.when(spy.isACertainValue())。thenReturn(true) ; 因为我想测试的是这种情况。

Mockito.when(spy.isACertainValue()).thenReturn(true); because that's the case I want to test.

但它不起作用,因为它仍在调用方法体:/

But it doesn't work as it is still calling the method-body :/

我得到了nullpointers,或者说我得到的东西

I get nullpointers or rather I get something along the lines of


误用。 WrongTypeOfReturnValue; getValueA()不能返回Boolean。
getValueA()应返回ValueA

misusing.WrongTypeOfReturnValue; Boolean cannot be returned by getValueA(). getValueA() should return ValueA

所以我尝试(作为解决方法):

So I tried (as a workaround) to do:

Mockito.when(contextMock.getValueA())。thenReturn(new ValueA());

Mockito.when(contextMock.getType())。thenReturn(ContextType.certainType);

但后来我得到了我似乎无法调试的nullpointer。

but then I get a nullpointer that I cant seem to be able to debug.

那么,在这种情况下如何正确完成?

So, how is it done right in this case?

推荐答案

当你调用时

Mockito.when(spy.isCertainValue()).thenReturn(true);

方法 isCertainValue()被调用这里。这就是Java的工作原理:要评估 Mockito.when 的参数, spy.isCertainValue()的结果必须因此必须调用该方法。

the method isCertainValue() is getting called here. This is how Java works: to evaluate the argument of Mockito.when, the result of spy.isCertainValue() must be evaluated so the method must be called.

如果您不希望这种情况发生,可以使用以下构造

If you don't want that to happen, you can use the following construct:

Mockito.doReturn(true).when(spy).isCertainValue();

这将具有相同的模拟效果,但不会使用此方法调用该方法。

This will have the same mocking effect but the method won't be called with this.

这篇关于如何在不运行方法的情况下模拟方法调用和返回值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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