簡體   English   中英

如何使用EasyMock模擬void方法,然后如何使用assert進行測試?

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

我需要對一個函數進行單元測試,該函數對另一個void方法進行內部調用。

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

我需要模擬someOtherClass.testMethod() ,然后使用assert驗證TestClass testMethod


對不起,如果我的帖子令人困惑。 讓我說得更清楚。 我的意圖是-

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. 
}

你寫的是有效的。 但是,它過於復雜,您無法驗證是否實際調用了void方法。 為此,您需要添加EasyMock.verify(obj); 在末尾。

然后,重要的一點是,如果在重播之前調用void方法,它將記錄一次調用。 無需添加expectLastCall 另外,您可能已經使用expectLastCall().andVoid()代替了IAnswer

這是我的寫法:

@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