java - @WebMvcTest 测试类中的 UnsatisfiedDependencyException

标签 java spring-boot junit spring-test spring-rest

在我将@Service 添加到 Controller 后,我的单元测试失败了。 该项目是 Spring-boot v 2.0.1.RELEASE。我花了很多时间试图找到答案,但没有运气。该测试在我添加 @Service 注释之前有效,并且我的服务类中有一个存储库。

堆栈跟踪:

2018-04-24 12:57:12.487 WARN 940 --- [ main] o.s.w.c.s.GenericWebApplicationContext : Exception encountered during context initialization - cancelling refresh attempt: org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'fleetController': Unsatisfied dependency expressed through field 'service'; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'uk.co.vw.lead.service.ContactUsService' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)}

Controller :

@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 组件的测试: Controller 。

因此无法 Autowiring 单元测试中声明的服务字段:

@Autowired
private ContactUsService service;

所以你也应该模拟这个依赖:

@MockBean
private ContactUsService service;

另请注意,由于 FleetControllerFleetRepository 没有任何直接依赖性,因此不需要模拟此 bean:

@MockBean
private FleetRepository repository;

更糟糕的是,它在上下文中添加了一个模拟,可能会在您的测试期间产生副作用。
您只需模拟被测 Controller 的直接依赖项。


作为替代方案,如果您只想模拟一些 bean 而不是所有不是 Controller 的 bean,请不要使用 @WebMvcTest 而不是使用 @SpringBootTest这将加载整个上下文。
然后在测试类中声明您要使用 @MockBean 模拟的类。

关于java - @WebMvcTest 测试类中的 UnsatisfiedDependencyException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50001424/

相关文章:

java - jps 不工作

java - 从 springBoot 应用程序中的子模块扫描包

java - JDBC 元数据获取十进制精度

spring-boot - SpringBoot 在运行 Junit 测试时禁用 DataSourceAutoconfigure 错误

java - junit:使用mockmvc测试 Controller 时注入(inject)bean上的NullPointer

java - 通常在大型 J2EE web 应用程序上,按模块清楚地分离应用程序。可能使用业务委托(delegate)模式

java - 如果类存在于类中,则 JNI 函数名称

java - 对多个字段施加唯一约束

java - 如何忽略像 "car":{}, 这样的空 json 对象,这些对象在使用 jackson 反序列化后会导致空的 pojo

java - 无法在单元测试的 Before 和 After 方法中启动/停止 Spark