【发布时间】:2014-02-13 05:43:19
【问题描述】:
在 API 文档中提到,在 strictmock 中默认启用顺序检查,而在 nice mock 的情况下则不是。我不明白他们所说的“订单检查”到底是什么意思。
【问题讨论】:
在 API 文档中提到,在 strictmock 中默认启用顺序检查,而在 nice mock 的情况下则不是。我不明白他们所说的“订单检查”到底是什么意思。
【问题讨论】:
如果你告诉一个 mock 期望调用 foo(),然后期望调用 bar(),而实际调用是 bar() 然后 foo(),一个严格的 mock 会抱怨,但一个好的 mock 赢了不。这就是订单检查的意思。
【讨论】:
EasyMock.createStrictMock() 创建一个模拟,并负责模拟将在适当的时候进行的方法调用的顺序。 考虑下面的例子: Click here for complete tutorial.
@Before
public void setUp(){
mathApplication = new MathApplication();
calcService = EasyMock.createStrictMock(CalculatorService.class);
mathApplication.setCalculatorService(calcService);
}
@Test
public void testAddAndSubtract(){
//add the behavior to add numbers
EasyMock.expect(calcService.add(20.0,10.0)).andReturn(30.0);
//subtract the behavior to subtract numbers
EasyMock.expect(calcService.subtract(20.0,10.0)).andReturn(10.0);
//activate the mock
EasyMock.replay(calcService);
//test the subtract functionality
Assert.assertEquals(mathApplication.subtract(20.0, 10.0),10.0,0);
//test the add functionality
Assert.assertEquals(mathApplication.add(20.0, 10.0),30.0,0);
//verify call to calcService is made or not
EasyMock.verify(calcService);
}
EasyMock.createNiceMock():如果多个方法具有相同的功能,我们可以创建NiceMock对象,只创建1个expect(method),可以创建多个assert(method1),assert(method2),...
@Before
public void setUp(){
mathApplication = new MathApplication();
calcService = EasyMock.createNiceMock(CalculatorService.class);
mathApplication.setCalculatorService(calcService);
}
@Test
public void testCalcService(){
//add the behavior to add numbers
EasyMock.expect(calcService.add(20.0,10.0)).andReturn(30.0);
//activate the mock
EasyMock.replay(calcService);
//test the add functionality
Assert.assertEquals(mathApplication.add(20.0, 10.0),30.0,0);
//test the subtract functionality
Assert.assertEquals(mathApplication.subtract(20.0, 10.0),0.0,0);
//test the multiply functionality
Assert.assertEquals(mathApplication.divide(20.0, 10.0),0.0,0);
//test the divide functionality
Assert.assertEquals(mathApplication.multiply(20.0, 10.0),0.0,0);
//verify call to calcService is made or not
EasyMock.verify(calcService);
}
【讨论】: