這是我在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();
}
}
}
我要找尋求你的幫助傢伙瞭解究竟發生了什麼
不確定是否因爲協作者在ClassTobeTested中被定義爲final。 –
可能是,但不知道如何解決這個問題在沒有修改ClassTobeTested的問題,因爲我不想碰我的ClassTobeTested只是因爲我不能單元測試相同的 – Muthu
至少證實相同。 –