我正在嘗試為以下服務方法 ( create())撰寫單元測驗:
public CommandDTO create(TaxLabelRequest taxLabelRequest) {
return saveTaxLabel(new TaxLabel(), taxLabelRequest);
}
private CommandDTO saveTaxLabel(TaxLabel taxLabel, TaxLabelRequest taxLabelRequest) {
taxLabel.setName(taxLabelRequest.getName());
// maybe I can use ArgumentCaptor for `taxLabel`
final TaxLabel saved = taxLabelRepository.saveAndFlush(taxLabel);
return CommandDTO.builder().uuid(saved.getUuid()).build();
}
這是我的單元測驗:
public void test_create() {
final TaxLabelRequest request = new TaxLabelRequest();
request.setCountryUuid(UUID.fromString("00000000-0000-0000-0000-000000000001"));
request.setName("Name");
TaxLabel taxLabel = new TaxLabel();
taxLabel.setCountryUuid(request.getCountryUuid());
taxLabel.setName(request.getName());
taxLabel.setDescription(request.getDescription());
when(taxLabelRepository.saveAndFlush(any())).thenReturn(taxLabel);
CommandDTO result = taxLabelService.create(request);
// I have no idea how to check the result
assertEquals(taxLabel.getUuid(), result.getUuid());
}
那么,我應該使用ArgumentCaptor以便獲取uuid保存物體的值,然后檢查它是否等于taxLabel.getUuid()?
uj5u.com熱心網友回復:
試試這個:
String myuuid = ...;
when(taxLabelRepository.saveAndFlush(request)).thenAnswer(new Answer(){
@Override
public Object answer(InvocationOnMock invocationOnMock) throws Throwable {
textLabel.setUuid(myuuid);
return textLabel;
}
});
CommandDTO result = taxLabelService.create(request);
assertEquals(myuuid, result.getUuid());
通過這種方式,您將測驗另外兩個方面:
- 使用
request代替any()您還可以驗證setName您在save呼叫之前插入的指令(顯然只有當該name欄位equals在TaxLabelRequest物件的實作中 具有自己的作用時)。 - 使用
Answer您正在驗證您正在查找的 UUID 是由使用正確request引數呼叫的保存操作設定的。
請注意,您可以Answer使用 lambda 函式替換匿名物件。
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/365018.html
