子模块中Autowired依赖项的NUnit 5 Spring MVC测试NoSuchBeanDefinitionExc



我有一个包含两个子模块的项目;一个是数据访问层,另一个是API服务。数据访问模块在服务类中使用JOOQ和自动连接的DSLContext。此外,我正在使用JUnit 5和Spring Boot 2.2.4。

数据访问模块中的QueryService类有一个类似@Autowired private DSLContext dsl的成员;

测试类设置如下:

@SpringBootTest
public class MyServiceTests {
@Autowired
QueryService service;
@Autowired
private DSLContext dsl;
@Test
public void TestDoSomething() throws Exception {
service.selectBusinessEntityRelatedByBusinessEntity("C00001234", mockAuth);
}
}

此模块中的测试运行正常。配置是从application.yaml中读取的,autowire将实际服务或mock注入到我的QueryService和本地dsl中。

API服务则是另一回事。如果我在没有MVC的情况下使用@SpringBootTest注释,我可以成功地让测试注入带有application.yaml配置的本地DSLContext。测试设置如下:

@SpringBootTest
public class CustomersControllerTests {
@Autowired
private Gson gson;
@Autowired
DSLContext dsl;
@Test
public void addCustomerTest() {
}

不过,我需要的是使用@WebMvcTest,以便初始化MockMvc,但切换到@WebMvcTest会导致在数据访问模块中实现的服务类中的注入失败。注入无法在查询服务类中找到DSLContext bean。我这样设置测试:

@WebMvcTest
public class CustomersControllerTests {
@Autowired
private MockMvc mockMvc;
@Autowired
private Gson gson;
private static final String testSub = "329e6764-3809-4e47-ac48-a52881045787";
@Test
public void addCustomerTest() {
var newCustomer = new Customer().firstName("John").lastName("Doe");
mockMvc.perform(post("/customers").content(gson.toJson(newCustomer)).contentType(MediaType.APPLICATION_JSON)
.with(jwt().jwt(jwt -> jwt.claim("sub", testSub)))).andExpect(status().isNotImplemented());
}

这是实际错误:

2020-02-25 18:14:33.655  WARN 10776 --- [           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 'customersController': Unsatisfied dependency expressed through field '_customersService'; nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'customersService': Unsatisfied dependency expressed through field '_queryService'; nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'queryService': Unsatisfied dependency expressed through field '_dsl'; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'org.jooq.DSLContext' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)}

所以,我知道测试应用程序配置是正确的,因为它在不使用MVC注释的情况下可以工作。此外,我可以在API项目测试中创建DSLContext,并且我可以在测试之外实际运行API服务。

那么,为什么在使用MVC测试设置时找不到DSLContext呢?

这可能是因为@WebMvcTest完全禁用了Spring Boot的自动配置,并且只扫描@Controllers和其他一些选择类,这是您的。。好MVC测试。。

Spring文档建议在您的情况下这样做:

如果你想加载完整的应用程序配置并使用MockMVC,你应该考虑将@SpringBootTest与@AutoConfigureMockMvc结合起来,而不是这个注释。

最新更新