3.1 doReturn()方法
现在魔法来了……
假设您创建了一个伪造的模拟对象,但您需要它以某种方式工作。当调用某些方法时,完成了一些重要的事情,或者这些方法返回了某个结果。该怎么办?
Mockito 库允许您将所需的行为添加到模拟对象。
如果你想让模拟对象在调用某个方法时返回某个结果,那么可以使用代码将这个“规则”添加到对象中:
Mockito.doReturn(result).when(an object).method name();
你看,在方法调用结束时,method name?
这里实际上没有进行任何调用。该方法doReturn()
返回一个特殊的代理对象,借助它监视对象方法的调用,从而编写规则。
再次。编写添加到模拟对象的规则真是一种聪明的方法。当你看到这样的代码时,需要一些技巧才能在你的脑海中正确地解释它。附带经验。
我认为需要一个具体的例子。让我们创建一个模拟类对象ArrayList
并要求其方法size()
返回数字 10。完整的代码如下所示:
@ExtendWith(MockitoExtension.class)
class DoReturnTest {
@Mock
List mockList;
@Test
public void whenMockAnnotation () {
//create a rule: return 10 when calling the size method
Mockito.doReturn(10).when(mockList).size();
//the method is called here and will return 10!!
assertEquals(10, mockList.size());
}
}
是的,这段代码可以工作,测试不会失败。
3.2 when()方法
还有另一种向模拟对象添加行为规则的方法——通过调用Mockito.when()
. 它看起来像这样:
Mockito.when(an object.method name()).thenReturn(result);
这与上一个编写模拟对象行为规则的方式相同。比较:
Mockito.doReturn(result).when(an object).method name();
这里发生了完全相同的事情——新规则的构建。
没错,第一个例子有两个缺点:
- 这个电话很混乱。
an object.method name()
methodname()
如果该方法返回 ,将不起作用void
。
好吧,让我们写下我们最喜欢的例子Mockito.when()
@ExtendWith(MockitoExtension.class)
class WhenTest {
@Mock
List mockList;
@Test
public void whenMockAnnotation() {
//create a rule: return 10 when calling the size method
Mockito.when(mockList.size() ).thenReturn(10);
//the method is called here and will return 10!!
assertEquals(10, mockList.size());
}
}
3.3 doThrow()方法
我们弄清楚了如何使模拟对象方法返回特定结果。我怎样才能让它抛出一个特定的异常?寄给doReturn()
?
为了防止方法返回,即抛出异常,您需要使用doThrow()
.
Mockito.doThrow(exception.class).when(an object).method name();
然后是第二个选项:
Mockito.when(an object.method name()).thenThrow(exception.class);
有点期待吧?
嗯,你看,你已经开始明白了。让我们用一个例子来修复它:
@ExtendWith(MockitoExtension.class)
class DoThrowTest {
@Mock
List mockList;
@Test
public void whenMockAnnotation() {
Mockito.when(mockList.size() ).thenThrow(IllegalStateException.class);
mockList.size(); //an exception will be thrown here
}
}
如果你需要抛出一个特定的异常对象,那么使用这种形式的构造:
Mockito.doThrow(new Exception()).when(an object).method name();
只需将doThrow()
异常对象传递给方法,它就会在方法调用期间抛出。
GO TO FULL VERSION