如何强制Mockito调用带有参数的底层函数?

huangapple go评论63阅读模式
英文:

How do I force Mockito to call underlaying functions with arguments?

问题

我有以下代码:

class MyClass {
    private String foo;
    public String getFoo() { return foo; }
    public void setFoo(String foo) { this.foo = foo; }
}

现在,我想对它进行模拟。

MyClass m = Mockito.mock(MyClass.class);
when(m.getFoo()).thenCallRealMethod();
when(m.setFoo(Mockito.anyString())).thenCallRealMethod();

但是这给了我这个编译错误:

'void' type not allowed here

使用 thenCallRealMethod() 似乎对没有参数的方法有效,但是我无法让它在有参数的方法上起作用。我做错了什么?

英文:

I have this:

class MyClass {
    private String foo;
    public getFoo() { return foo; }
    public setFoo(String foo) { this.foo = foo; }
}

Now, I want to mock it.

MyClass m = Mockito.mock(MyClass.class);
when(m.getFoo()).thenCallRealMethod();
when(m.setFoo(Mockito.anyString())).thenCallRealMethod(); 

But this gives me this compile error:

'void' type not allowed here

Using thenCallRealMethod() seems to work for methods with no arguments, but I cannot get it to work with arguments. What am I doing wrong?

答案1

得分: 2

因为无返回值的方法无法返回任何内容,包括 Mockito 的 matcher,所以您需要使用不同的语法来处理这些情况:

doCallRealMethod().when(m).setFoo(Mockito.anyString());
英文:

Since void methods cannot return anything, including a mockito matcher, you need to use a different syntax for those:

doCallRealMethod().when(m).setFoo(Mockito.anyString())

答案2

得分: 1

你还可以对该对象进行监视,这只会模拟已定义的方法。

更多信息请参见使用Mockito模拟部分方法而不是其他方法

英文:

You could also spy on the object, this will only mock the defined methods

For further information Use Mockito to mock some methods but not others

huangapple
  • 本文由 发表于 2020年10月5日 18:07:33
  • 转载请务必保留本文链接:https://go.coder-hub.com/64206541.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定