2013-04-16 91 views
0

這是我在Stackoverflow的第一篇文章,到目前爲止我一直是這個論壇的活躍讀者,我在這裏發佈我的第一個問題。EasyMock模擬方法調用在重置模擬對象後第二次調用時返回null

這是關於EasyMock的用法,我是EasyMock的新用戶,在下面的示例代碼中,我設置了一個合作者方法的期望值,並返回相同的對象(無論它是相同的對象還是不同的對象,但結果是一樣的),並在重新開始測試方法之前進行重置。但是當第二個測試執行時,模擬方法返回null,我不知道爲什麼會發生這種情況。

如果我運行的方法

@RunWith(PowerMockRunner.class) 
@PrepareForTest({CollaboratorWithMethod.class, ClassTobeTested.class}) 
public class TestClassTobeTested { 

private TestId testId = new TestId(); 

@Test 
public void testMethodtoBeTested() throws Exception{ 
    CollaboratorWithMethod mockCollaborator = EasyMock.createMock(CollaboratorWithMethod.class); 
    PowerMock.expectNew(CollaboratorWithMethod.class).andReturn(mockCollaborator); 
    EasyMock.expect(mockCollaborator.testMethod("test")).andReturn(testId); 
    PowerMock.replay(CollaboratorWithMethod.class); 
    EasyMock.replay(mockCollaborator); 
    ClassTobeTested testObj = new ClassTobeTested(); 
    try { 
     testObj.methodToBeTested(); 
    } finally { 
     EasyMock.reset(mockCollaborator); 
     PowerMock.reset(CollaboratorWithMethod.class); 
    } 
} 

@Test 
public void testMothedtoBeTestWithException() throws Exception { 
    CollaboratorWithMethod mockCollaborator = EasyMock.createMock(CollaboratorWithMethod.class); 
    PowerMock.expectNew(CollaboratorWithMethod.class).andReturn(mockCollaborator); 
    EasyMock.expect(mockCollaborator.testMethod("test")).andReturn(testId); 
    PowerMock.replay(CollaboratorWithMethod.class); 
    EasyMock.replay(mockCollaborator); 
    ClassTobeTested testObj = new ClassTobeTested(); 
    try { 
     testObj.methodToBeTested(); 
    } finally { 
     EasyMock.reset(mockCollaborator); 
     PowerMock.reset(CollaboratorWithMethod.class); 
    } 
} 

}

這裏是我的合作者類

public class CollaboratorWithMethod { 
    public TestId testMethod(String text) throws IllegalStateException { 
    if (text != null) { 
     return new TestId(); 
    } else { 
     throw new IllegalStateException(); 
    } 
    } 
} 

,這裏是我的測試類

public class ClassTobeTested { 

public static final CollaboratorWithMethod collaborator = new CollaboratorWithMethod(); 

public void methodToBeTested() throws IOException{ 
    try { 
     TestId testid = collaborator.testMethod("test"); 
     System.out.println("Testid returned "+ testid); 
    } catch (IllegalStateException e) { 
     throw new IOException(); 
    } 
} 
} 

我要找尋求你的幫助傢伙瞭解究竟發生了什麼

+0

不確定是否因爲協作者在ClassTobeTested中被定義爲final。 –

+0

可能是,但不知道如何解決這個問題在沒有修改ClassTobeTested的問題,因爲我不想碰我的ClassTobeTested只是因爲我不能單元測試相同的 – Muthu

+0

至少證實相同。 –

回答

0

collaborator變量ClassTobeTested是最終的。第一個測試用例用模擬對象初始化變量。第二個測試用例不能再次初始化該變量。您在第二個測試用例中創建的模擬對象上設置期望值,但實際上該變量仍然指的是第一個模擬對象。

由於您不想修改該類,因此應該使用@BeforeClass設置一次模擬引用,並將「mockCollaborator」設置爲全局變量,以便可以在多個測試用例中使用該引用。

+0

是的,謝謝你的解釋,解決了我的問題。但是當我們期待第二種測試方法中的結構再次出現時,我希望PowerMock報告一些錯誤。我也嘗試使用WhilteBox.setInternalState,即使我試圖在不同的測試方法中爲最終的varibale設置不同的對象,也可以很好地工作。無論如何,非常感謝您的幫助。 – Muthu

相關問題