尝试运行测试但最终出现标题中的错误。我正在一个 springboot 项目中工作。该项目运行良好,没有任何问题。当我尝试运行测试时,它抛出错误。
在测试文件夹中添加依赖的ValidationService类
java包内部
@Service
public class ValidationService {
@Autowired
TicketDetailRepository ticketDetailRepository;
public boolean isValidTicket(Long ticketId)
{
Optional<TicketDetailEntity> optionalTicketDetailEntity = ticketDetailRepository.findById(ticketId);
if(optionalTicketDetailEntity.isPresent())
{
return optionalTicketDetailEntity.get().getTicketStatus();
}
else
{
return false;
}
}
}
@RestController
@RequestMapping(path = "/xxx")
public class ValidationController {
@Autowired
ValidationService validationService;
@RequestMapping("validate")
public ValidationResponse validate(@RequestBody @Valid ValidationRequest validationRequest) {
return true;
}
}
测试包内部
@RunWith(SpringRunner.class)
@WebMvcTest(controllers = { ValidationController.class }, secure = false)
@Import(ExceptionHandlerConfiguration.class)
public class ValidationControllerIntegrationTest {
@Autowired
MockMvc mockMvc;
@Autowired
ObjectMapper objectMapper;
@Autowired
RequestMappingHandlerAdapter adapter;
@Test
public void xxx() throws Exception {
ValidationRequest validationRequest = ValidationRequest.builder().build();
jsonPost("xxx", validationRequest)
.andExpect(status().isOk())
.andExpect(jsonPath("xxx").value(true))
.andExpect(status().isOk())
.andExpect(jsonPath("xxx").value(false));
}
ResultActions jsonPost(String url, Object entity) throws Exception {
return
this.mockMvc.perform(MockMvcRequestBuilders
.post(url)
.contentType(MediaType.APPLICATION_JSON)
.content(objectMapper.writeValueAsString(entity))
)
.andDo(MockMvcResultHandlers.print());
}
}
预期:不应抛出错误 实际:运行测试时抛出不满足的依赖错误。
最佳答案
您应该提供完整的错误。目前尚不清楚哪个 bean 未初始化。 一项建议是在 ValidationService 的测试类上添加 @ComponentScan。
喜欢 @ComponentScan ({"PACKAGE_NAME_WHERE_ValidationService_IS_Resides"})
关于java - 由 : org. springframework.beans.factory.NoSuchBeanDefinitionException 引起:运行测试时,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57656641/