在API文档中提到,在strictmock中默认启用顺序检查,而在nice mock中则不启用。我不明白他们所说的“order checking”具体是什么意思。
如果你告诉一个模拟对象期望调用foo()
,然后期望调用bar()
,但实际的调用顺序是bar()
然后foo()
,一个严格的模拟对象会抱怨,但一个友好的模拟对象不会。这就是所谓的顺序检查。
EasyMock.createStrictMock() 创建一个模拟对象,并且会在模拟对象执行期间自动处理方法调用的顺序。 考虑下面的例子: 点击此处获取完整教程。
@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);
}