【发布时间】:2017-07-04 09:54:49
【问题描述】:
假设,我有一个测试类,有两种方法如下:
public class TestClass {
@Mock
TestClass testObject;
@Test
public void method1() {
doReturn("str").when(testObject).method2();
String s1 = testObject.method2(); // This line gives compilation
//error. Type mismatch cannot convert from void to string
}
@Test
public void method2() {
}
我基本上是在尝试模拟 method2,它是 method1 中的一个依赖项。
但如您所见,method2 返回类型为 void。所以,我使用 doReturn 来模拟它。
据我了解,虽然 method2 的返回类型是 void,但在我模拟后,method2 的模拟版本应该返回 String 类型。
但是,正如我在方法 1 中评论的那样,它给出了类型不匹配。
【问题讨论】:
-
@D.Peter doReturn/when 用于模拟 void 方法。我正在尝试做同样的事情,但必须知道我错过了什么..
标签: unit-testing junit mockito