![](/img/trans.png)
[英]How to mock a value to test a conditional in another method with JUnit/Mockito?
[英]How to verify mock method parameter of class type contains a value using mockito for junit
我有一個服務單元測試,我需要模擬一個 Dao,但我還需要驗證 class 類型屬性studyRefActive的方法參數包含一個值“Y”
RegDao class:
public class RegDao {
----
----
public void save(Study study){
//DB call to insert
}
}
注冊服務 class:
public class RegService {
private RegDao regDao;
//Inject dao here
public void saveStudy(Study study){
//some data assignements
study.setStudyRefActive("Y");
regDao.save(study);
}
}
我的單元測試:
RegDao mockRegDao = mock(RegDao.class);
RegService regService = new RegService(mockRegDao);
Study study = new Study();
Mockito.doNothing.when(mockRegDao).saveStudy(any(Study.class));
regService.saveData(study)
所以我的問題是如何驗證 Study DTO 的屬性 studyRefActive 的值為“Y”?
幫助贊賞!
您可以使用 ArgumentCaptor。 下面我詳細說說:
RegDao mockRegDao = mock(RegDao.class);
RegService regService = new RegService(mockRegDao);
Study study = new Study();
//I think you can remove the line below. Please test it on your implementation.
Mockito.doNothing.when(mockRegDao).saveStudy(any(Study.class));
regService.saveData(study);
ArgumentCaptor<Study> studyArgumentCaptor = ArgumentCaptor.forClass(Study.class);
Mockito.verify(mockRegDao).save(studyArgumentCaptor.capture());
//here you are going to retrieve the value that was sent as a parameter to the method "save" of RegDao class.
Study savedStudy = studyArgumentCaptor.getValue();
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.