EasyMock.createStrictMock(class<T> x)和EasyMock.createNiceMock(class<T> x)之间的区别

6

在API文档中提到,在strictmock中默认启用顺序检查,而在nice mock中则不启用。我不明白他们所说的“order checking”具体是什么意思。

2个回答

14

如果你告诉一个模拟对象期望调用foo(),然后期望调用bar(),但实际的调用顺序是bar()然后foo(),一个严格的模拟对象会抱怨,但一个友好的模拟对象不会。这就是所谓的顺序检查。


不过,如果在模拟对象上调用bear()函数,一个好的模拟将使用未模拟的bear()函数实现而不会抱怨。严格模拟将... - Hobbamok

0

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接