Mokito

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);

 

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值