我想單元測試下面的方法如何使用thenAnswer與方法,該方法返回void
public void addRecord(Record record)
{
Myclass newObj = new Mycalss();
// It creates newObj object, set some values using record object.
// and it adds the newObj in daatbase.
dataReqDao.persist(newObj);
}
我都嘲笑dataReqDao.persist
方法,但我怎麼能驗證是否正確的值複製到newObj對象?我想獲得newObj對象。
我認爲thenAnswer
將是檢索newObj ie方法參數但不知道如何使用它返回void的方法的方法。
更新:
我試圖
doAnswer(new Answer<Myclass>() {
public Myclass answer(InvocationOnMock invocation) {
Object[] args = invocation.getArguments();
return (Myclass)args[0];
}
}).when(dataReqDao.persist(any(Myclass.class)));
編輯:
它應該是(感謝大衛)
doAnswer(new Answer<Myclass>() {
public Myclass answer(InvocationOnMock invocation) {
Object[] args = invocation.getArguments();
return (Myclass)args[0];
}
}).when(dataReqDao).persist(any(Myclass.class));
在您的更新,括號內是在錯誤的地方。我不確定這是不是你的錯誤的原因,因爲其餘部分看起來不錯。所以它應該是'doAnswer(...).when(dataReqDao).persist(...);'這有幫助嗎? – 2012-01-10 22:56:41
@David:謝謝大衛。其實我糾正了,但忘記更新我的問題。 – xyz 2012-01-11 05:45:41