简体   繁体   English

如何验证 class 类型的模拟方法参数包含使用 mockito 的值 junit

[英]How to verify mock method parameter of class type contains a value using mockito for junit

I have a service unit test, where I need to mock a Dao but also i need to verify the method parameter of class type property studyRefActive contains a value "Y"我有一个服务单元测试,我需要模拟一个 Dao,但我还需要验证 class 类型属性studyRefActive的方法参数包含一个值“Y”

RegDao class: RegDao class:

public class RegDao {
----
----
public void save(Study study){
  //DB call to insert 
}

}

RegService class:注册服务 class:

public class RegService {

private RegDao  regDao;
 //Inject dao here 

  public void saveStudy(Study study){
    
     //some data assignements
    study.setStudyRefActive("Y");
    regDao.save(study);

   }


}

my unit test:我的单元测试:

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)

so my question is how can i validate the Study DTO has the value 'Y' for the property studyRefActive?所以我的问题是如何验证 Study DTO 的属性 studyRefActive 的值为“Y”?

Help Appreciated!帮助赞赏!

You can use an ArgumentCaptor.您可以使用 ArgumentCaptor。 Let me elaborate below:下面我详细说说:

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM