简体   繁体   中英

How to mock void method using EasyMock and then how to test it using assert?

I need to unit test a function, which makes an inner call of another void method.

Class TestClass {
    public void testMethod() {
        someOtherClass.testMethod(); // This is void method 
    }
}

I need to mock someOtherClass.testMethod() and then verify testMethod of TestClass using assert.


Sorry for my post if it is confusing. Let me make it more clear. My intention is -

public void testMethodTest() { 
  TestClass tC = new TestClass(); SomeOtherClass obj = EasyMock.createNiceMock(SomeOtherClass.class); 
  tC.set(obj); 
  obj.testMethod(); 
  EasyMock.expectLastCall().andAnswer(new IAnswer() { 
     public Object answer() { // return the value to be returned by the method (null for void) 
       return null; 
     }
  }); 
  EasyMock.replay(obj); 
  tC.testMethod(); // How to verify this using assert. 
}

What you wrote is working. However, it is overly complicated and you are not verifying that the void method was actually called. To do that, you need to add EasyMock.verify(obj); at the end.

Then, one important thing is that if you call a void method before the replay, it records a call. No need to add an expectLastCall . Also, you could have used expectLastCall().andVoid() instead of the IAnswer .

Here is how I would write it:

@Test
public void testMethodTest() {
  TestClass tC = new TestClass();
  SomeOtherClass obj = mock(SomeOtherClass.class); // no need to use a nice mock
  tC.set(obj);

  obj.testMethod();

  replay(obj);

  tC.testMethod();

  verify(obj); // Verify testMethod was called
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM