1@Mock
创建一个mock
或者
calcService = mock(CalculatorService.class);
2@InjectMocks: 创建一个实例,其余用@Mock(或@Spy)注解创建的mock将被注入到用该实例中。
注意:必须使用@RunWith(MockitoJUnitRunner.class) 或 Mockito.initMocks(this)进行mocks的初始化和注入
3mock添加对象和行为
Mockito 使用when()的方法向模拟对象添加功能。查看下面的代码段。
when(calcService.add(10.0,20.0)).thenReturn(30.00);
在这里, 我们已经指示 Mockito 给add方法calcService添加10和20的行为, 结果是返回30.00 的值。
在这个时间点, Mock记录的行为, 是一个工作的模拟对象。
4verify:验证是否使用required参数调用模拟方法
//test the add functionality Assert.assertEquals(mathApplication.add(10.0, 20.0),30.0,0); //verify call to calcService is made or not with same arguments. verify(calcService).add(10.0, 20.0);
5检查预期调用次数
Mockito 对可对特定方法进行的调用数检查。假设 MathApplication 只调用 CalculatorService. serviceUsed () 方法一次, 则它不应该能够调用 CalculatorService. serviceUsed () 多余一次。
/add the behavior of calc service to add two numbers when(calcService.add(10.0,20.0)).thenReturn(30.00); //limit the method call to 1, no less and no more calls are allowed verify(calcService, times(1)).add(10.0, 20.0);
Mockito 提供了以下附加方法来更改预期的调用计数。
-
atLeast (int min) −期望最小调用。
-
atLeastOnce () −希望至少有一个调用。
-
atMost (int max) −期望最大调用。
//verify that method was never called on a mock
verify(calcService, never()).multiply(10.0,20.0);
5异常
Mockito 提供了一个模拟抛出异常的功能, 因此可以测试异常处理。查看下面的代码段。
//add the behavior to throw exception doThrow(new Runtime Exception("divide operation not implemented")) .when(calcService).add(10.0,20.0);
在这里, 我们向模拟对象添加了一个异常子句。MathApplication 使用 calcService 的 add 方法, 当调用 calcService. add () 方法时, 该模拟会抛出一个 RuntimeException。
6順序验证
Mockito 提供了一个Inorder 类, 它负责处理在适当的时间内模拟将要做出的方法调用的顺序。
//create an inOrder verifier for a single mock InOrder inOrder = inOrder(calcService); //following will make sure that add is first called then subtract is called. inOrder.verify(calcService).add(20.0,10.0); inOrder.verify(calcService).subtract(20.0,10.0);