2011-09-03 312 views
1

我有一個將被測試代碼:JUnit測試:靜態方法調用到測試方法

public void ackAlert(final Long alertId, final String comment) { 
    final AnyTask task = AnyTask.create(
      "ackAlert", new Class[] { Long.class, String.class }, 
      new Object[] { alertId, comment }); 
    taskExecutor.execute(task); 
} 

我書面方式測試它:

public void testAckAlert() throws Exception { 

    final Long alertId = 1L; 
    final String comment = "tested"; 

    final AnyTask task = AnyTask.create(
    "ackAlert", new Class[] { Long.class, String.class }, 
    new Object[] { alertId, comment }); 

    taskExecutor.execute(task); 
    expectLastCall(); 

    replay(taskExecutor); 

    testingObjectInstance.ackAlert(alertId, comment); 

    verify(taskExecutor); 

} 

而且我得到異常:

java.lang.AssertionError: Unexpected method call execute([email protected]): execute([email protected]): expected: 1, actual: 0

我的錯誤在哪裏?我覺得問題是在調用靜態方法創建

+0

蘇爾有沒有Java的隔離/模擬框架,不需要過時的記錄/重放語法? – TrueWill

+0

真的嗎?你建議哪一個? –

+0

我沒有在Java領域的建議;我是C#開發人員。 Java開源工具通常更成熟,所以這讓我感到驚訝。我希望Java專家可以建議一個不同的庫。 – TrueWill

回答

0

我沒有看到你在創建你的模擬,但是,嘲笑靜態方法調用不能用EasyMock完成。但是,PowerMock可以與EasyMock或Mockito一起使用至mock a static method call

您需要用@RunWith(PowerMockRunner.class)@PrepareForTest(AnyTask.class)註釋您的測試類。然後,你的測試將是這個樣子:

public void testAckAlert() throws Exception { 

    final Long alertId = 1L; 
    final String comment = "tested"; 
    mockStatic(AnyTask.class); 

    final AnyTask task = new AnyTask(); 
    expect(AnyTask.create(
    "ackAlert", new Class[] { Long.class, String.class }, 
    new Object[] { alertId, comment })).andReturn(task); 

    taskExecutor.execute(task); 
    expectLastCall(); 

    replay(AnyTask.class, taskExecutor); 

    testingObjectInstance.ackAlert(alertId, comment); 

    verify(taskExecutor); 

} 
1

它可能不是重要嘲笑你的靜態方法,這取決於它是什麼,你想測試。該錯誤是因爲它看不到在您測試的方法中創建的任務等於您傳遞給模擬的任務。

你可以在AnyTask上實現equals和hashCode,以便它們看起來是等價的。在測試之後,您還可以「捕獲」傳遞的任務以執行並驗證相關內容。這將是這樣的:

public void testAckAlert() throws Exception { 

    final Long alertId = 1L; 
    final String comment = "tested"; 
    mockStatic(AnyTask.class); 

    Capture<AnyTask> capturedTask = new Capture<AnyTask>(); 

    taskExecutor.execute(capture(capturedTask)); 
    expectLastCall(); 

    replay(taskExecutor); 

    testingObjectInstance.ackAlert(alertId, comment); 

    AnyTask actualTask = capturedTask.getValue(); 
    assertEquals(actualTask.getName(), "ackAlert"); 
    verify(taskExecutor); 

} 

如果你是不是真的測試有關的任務什麼,但只是在taskExecutor.execute()被調用時,你可以簡單地更換

taskExecutor.execute(task); 

taskExecutor.execute(isA(AnyTask.class)); 

或甚至

taskExecutor.execute(anyObject(AnyTask.class));