java - @WebMvcTest 测试类中的 UnsatisfiedDependencyException
问题描述
将@Service 添加到控制器后,我的单元测试失败。该项目是 Spring-boot v 2.0.1.RELEASE。我花了很多时间试图找到答案,但没有运气。在我添加 @Service 注释并且我的服务类中有一个存储库之前,该测试有效。
堆栈跟踪:
2018-04-24 12:57:12.487 WARN 940 --- [main] oswcsGenericWebApplicationContext:在上下文初始化期间遇到异常 - 取消刷新尝试:org.springframework.beans.factory.UnsatisfiedDependencyException:创建名为“fleetController”的 bean 时出错:不满意通过字段“服务”表达的依赖关系;嵌套异常是 org.springframework.beans.factory.NoSuchBeanDefinitionException:没有“uk.co.vw.lead.service.ContactUsService”类型的合格 bean 可用:预计至少有 1 个有资格作为自动装配候选者的 bean。依赖注解:{@org.springframework.beans.factory.annotation.Autowired(required=true)}
控制器:
@Slf4j
@RestController
@RequestMapping(value = VERSION, consumes = MediaType.APPLICATION_FORM_URLENCODED_VALUE)
public class FleetController {
public static final String VERSION = "1.0";
@Autowired
private ContactUsService service;
@InitBinder
public void initBinder(final WebDataBinder webDataBinder) {
webDataBinder.registerCustomEditor(NatureOfEnquiryEnum.class, new NatureOfEnquiryEnumConverter());
webDataBinder.registerCustomEditor(FleetSizeEnum.class, new FleetSizeEnumConverter());
}
@PostMapping(value = "/fleet/contact-us")
public ResponseEntity contactUs(@Valid ContactUsDTO formDTO) {
service.createForm(formDTO);
return new ResponseEntity(HttpStatus.NO_CONTENT);
}
@PostMapping(value = "/fleet/request-demo")
public ResponseEntity requestDemo(@Valid RequestDemoDTO demoDTO) {
return new ResponseEntity(HttpStatus.NO_CONTENT);
}
服务:
@Service
public class ContactUsServiceImpl implements ContactUsService {
@Autowired
private FleetRepository repository;
@Override
public void createForm(ContactUsDTO formDTO) {
ContactUsForm form = populateContactUsForm(formDTO);
repository.save(form);
}
}
测试类:
@RunWith(JUnitPlatform.class)
@WebMvcTest(FleetController.class)
@ExtendWith(SpringExtension.class)
public class FleetControllerTest {
private final String CONTACT_US_URL = "/fleet/contact-us";
@Autowired
private MockMvc mockMvc;
@MockBean
private FleetRepository repository;
@Autowired
private ContactUsService service;
@Test
public void contactUsSuccessTest() throws Exception {
this.mockMvc.perform( post("/" + VERSION + CONTACT_US_URL)
.contentType(MediaType.APPLICATION_FORM_URLENCODED_VALUE)
.param("firstname", "John")
.param("lastname", "Doe")
.param("company", "Skynet")
.param("emailAddress", "john.connor@sky.net")
.param("telephone", "020 8759 4294")
.param("natureOfEnquiry", "new")
.param("comments", "some comments")
.param("recaptchaResponse", "success"))
.andExpect(status().isNoContent());
}
@Test
public void contactUsMissingRequiredFieldsTest() throws Exception {
this.mockMvc.perform( post("/1.0/fleet/contact-us")
.contentType(MediaType.APPLICATION_FORM_URLENCODED_VALUE))
.andExpect(status().isBadRequest());
}
}
请帮忙,因为我不知道发生了什么。
解决方案
带有注释@WebMvcTest
的测试类是 仅关注 Spring MVC 组件的测试:控制器。
因此,您的单元测试中声明的服务字段无法自动装配:
@Autowired
private ContactUsService service;
所以你也应该模拟这个依赖:
@MockBean
private ContactUsService service;
另请注意,由于FleetController
没有任何直接依赖FleetRepository
,因此不需要模拟此 bean:
@MockBean
private FleetRepository repository;
更糟糕的是,它在上下文中添加了一个模拟,这可能会在您的测试期间产生副作用。
您只需模拟被测控制器的直接依赖项。
作为替代方案,如果您只想模拟一些bean 而不是所有不是控制器的bean,请不要使用@WebMvcTest
and 而不是使用@SpringBootTest
它将加载整个上下文。
然后在测试类中声明要模拟的类@MockBean
。
推荐阅读
- swift - 具有 Any 和 Associated 类型的协议函数
- php - 有没有办法在 WordPress 中生成 pdf 证书并发送到电子邮件
- javascript - 我们如何在 react-native 中使用多线程
- python - 如何在 python 回调中将变量设置为变量,而不是在“输出”html.Div 中
- c++ - 如何将 VS2019 C++ 编译器添加到 VSCode?
- ios - iOS ARKit4 - 如何修复 ARCamera 的白平衡?
- html - 如何使跨度转到下一行
- c++ - AutoHotkey 之类的程序如何防止 Windows 热键?
- ios - Flutter ios app在发布模式下显示白屏?
- ios - 应用元数据因 Core NFC 而被拒绝,但未在应用代码或 pod 代码中的任何地方使用