如何解决即使使用doReturn
我想创建一个集成测试,其中在控制器上调用put方法并更新某个对象。在此过程中,将涉及一个服务类,该服务类调用第三方API来完成某些工作。就我而言,我想对调用第三方所涉及的服务方法进行存根,因为这不是测试第三方的重点。
话虽如此,我将展示我的代码,并等待一个答案,为什么它不能按预期和/或任何其他解决方法工作。
这是我的服务类,是我想存根的方法调用。
public class ProjectService implements SomeInterfance {
// the third party service
private final DamConnector damConnector;
// some other fields
public ProjectDTO save(ProjectDTO projectDTO) {
log.debug("Request to save Project : {}",projectDTO);
// some operations
synchronizeWithDamAndSave(project,parentChanging); //this is the method call I want to be skiped
//other operations
return projectMapper.toDto(project,this);
}
//the method that I want to stub
public Asset synchronizeWithDamAndSave(Project project,boolean includeDocuments) {
Asset asset = synchronizeWithDam(project,includeDocuments);
projectRepository.save(project);
return asset;
}
}
还有我的综合测试课:
@SpringBootTest(classes = SppApp.class)
public class ProjectResourceIT {
//other fields
//my service use autowire as it needs to make the service calls
@Autowired
private ProjectService projectService;
//this is my setup method where I create the spy of project service and define the doReturn behavior when my method is called
@BeforeEach
public void setup() {
ProjectService spyProjectService = Mockito.spy(projectService);
Mockito.doReturn(new Asset()).when(spyProjectService).synchronizeWithDamAndSave(Mockito.any(Project.class),Mockito.anyBoolean());
MockitoAnnotations.initMocks(this);
final ProjectResource projectResource = new ProjectResource(spyProjectService,clientService,securityService);
this.restProjectMockMvc = MockMvcBuilders.standaloneSetup(projectResource)
.setCustomArgumentResolvers(pageableArgumentResolver)
.setControllerAdvice(exceptionTranslator)
.setConversionService(createFormattingConversionService())
.setMessageConverters(jacksonMessageConverter)
.setValidator(validator).build();
}
}
...
public void updateProject() throws Exception {
// initialization of the test
// this is where I call my controller
restProjectMockMvc.perform(put("/api/projects")
.contentType(TestUtil.APPLICATION_JSON_UTF8)
.content(TestUtil.convertObjectToJsonBytes(projectDTO)))
.andExpect(status().isOk());
}
}
在我的情况下,问题是模仿在紧随其后的 synchronizeWithDamAndSave 方法中输入
Mockito.doReturn(新Asset())。何时(spyProjectService).synchronizeWithDamAndSave(Mockito.any(Project.class),Mockito.anyBoolean());
在要从其余api调用的方法之前调用此行。
我该怎么办?有关为什么会发生这种情况的任何提示?
解决方法
Spring Boot的代理无法与Mockito一起使用。使用@SpyBean而不是@Autowired。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。