Difference between EasyMock.createStrictMock(class<T> x) and EasyMock.createNiceMock(class<T> x)

StackOverflow https://stackoverflow.com/questions/21746164

  •  10-10-2022
  •  | 
  •  

Question

In the API doc it is mentioned that in the strictmock order checking is enabled by default while in case of nice mock it is not . I did not get what exactly they meant by "order checking".

Was it helpful?

Solution

If you tell a mock to expect a call to foo(), then to expect a call to bar(), and the actual calls are bar() then foo(), a strict mock will complain but a nice mock won't. That's what order checking means.

OTHER TIPS

EasyMock.createStrictMock() creates a mock and also takes care of the order of method calls that the mock is going to make in due course of its action. Consider below example: 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(): If multiple methods have same functionality, we can create NiceMock object and create only 1 expect(method) and can create multiple 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);
   }
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top