简体   繁体   English

如何使用EasyMock模拟void方法,然后如何使用assert进行测试?

[英]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. 我需要对一个函数进行单元测试,该函数对另一个void方法进行内部调用。

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. 我需要模拟someOtherClass.testMethod() ,然后使用assert验证TestClass testMethod


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. 但是,它过于复杂,您无法验证是否实际调用了void方法。 To do that, you need to add EasyMock.verify(obj); 为此,您需要添加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. 然后,重要的一点是,如果在重播之前调用void方法,它将记录一次调用。 No need to add an expectLastCall . 无需添加expectLastCall Also, you could have used expectLastCall().andVoid() instead of the IAnswer . 另外,您可能已经使用expectLastCall().andVoid()代替了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
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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