【问题标题】:How to exclude a @Configuration class when using @WebMvcTest with spring-boot?将@WebMvcTest 与spring-boot 一起使用时如何排除@Configuration 类?
【发布时间】:2020-02-17 06:02:06
【问题描述】:

我正在为休息控制器编写 junits。我只想加载与控制器相关的最小上下文,我认为这就是@WebMvcTest 加载上下文的方式。但是 junit 正在加载完整的 Spring 上下文,并且由于某些 bean 无法创建而失败。

我已经搜索并阅读了许多有关 stackoverflow 的问题,但没有一个解决方案可以排除特定配置。为控制器编写联结时如何加载最小上下文?或者有什么办法可以排除一些配置类?我正在使用 Spring-boot 2.2.2.RELEASE、Java 8 和 Junit 4。

Junit(我试图排除加载一些 bean 和配置但它不起作用):

@RunWith(SpringRunner.class)
@WebMvcTest(controllers = OrderController.class, excludeFilters = {@Filter(classes = Configuration.class), @Filter(type = FilterType.REGEX, pattern = "com\\.foo\\..*")})
@TestPropertySource(properties = { "spring.cloud.config.server.bootstrap:false" })
public class OrderControllerTest {

    @MockBean
    private OrderService orderService;


    @Autowired
    private MockMvc mockMvc;

    @Test
    public void test() throws Exception {
        mockMvc.perform(get("/internal/order/123"));
        // Further code to verify the response
    }

}

控制器

@Slf4j
@Validated
@RestController
@RequestMapping("/internal")
public class OrderController {

    @Autowired
    private OrderService orderService;

    @GetMapping(value = "/order/{orderId}", produces = { MediaType.APPLICATION_JSON_VALUE })
    public ResponseEntity<RegularContributionOrder> retrieveRegularContributionOrder(@NotNull @PathVariable("orderId") String orderId)
            throws OrderNotFoundException {

        RegularContributionOrder order = orderService.retrieve(orderId);

        return new ResponseEntity<RegularContributionOrder>(order, HttpStatus.OK);
    }
}

我想从上下文加载中排除的配置类

@Slf4j
@Configuration
@EnableAspectJAutoProxy
@ImportResource({ "classpath:spring/service-config-one.xml", "classpath:spring/service-config-two.xml" })
public class OrderServiceConfig {

    @Bean
    public MessageSource messageSource() {
        ReloadableResourceBundleMessageSource messageSource = new ReloadableResourceBundleMessageSource();
        messageSource.setBasename("classpath:resourcebundles/error-messages.properties");
        messageSource.setDefaultEncoding("UTF-8");
        return messageSource;
    }

    @Bean
    public ObjectMapper objectMapper() {
        ObjectMapper mapper = new ObjectMapper();
        return mapper;
    }
}

Spring boot 主类:

@EnableJms
@EnableAspectJAutoProxy
@ComponentScan(basePackages = { "com.foo.services", "com.bar" })
@SpringBootApplication(exclude = { SomeConfiguration.class})
public class BootApplication extends SpringBootServletInitializer {

    @Override
    protected final SpringApplicationBuilder configure(final SpringApplicationBuilder application) {
        return application.sources(BootApplication .class);
    }

    public static void main(final String[] args) {
        TimeZone.setDefault(TimeZone.getTimeZone("UTC"));
        SpringApplication.run(BootApplication.class, args);
    }
}

【问题讨论】:

  • 你能分享一下你用@SpringBootApplication注释的主类吗?
  • @AndyWilkinson 感谢您的评论。问题已更新。

标签: java spring-boot junit4


【解决方案1】:

您对@ComponentScan 的使用已禁用@WebMvcTest 使用的过滤器来限制通过扫描找到的组件类型。

您应该从主应用程序类中删除 @ComponentScan,并改用 @SpringBootApplication 上的 basePackages 属性。

您还应该将@EnableJms@EnableAspectJAutoProxy 移至单独的@Configuration 类,以便在使用@WebMvcTest 时不会启用它们。或者,您可以完全删除它们,因为它们已被 Spring Boot 的自动配置所覆盖。

【讨论】:

  • 效果惊人。它应该是@SpringBootApplication 中的参数“basePackages”而不是“backPackages”。可能是一个小错字
  • 谢谢@Prometheus。我已经修正了错字。
【解决方案2】:

当您的测试类位于测试文件夹中并使用“测试”配置文件运行时,您的真实配置类将被排除在外。这是我如何配置 Spring Boot 测试的示例。

@RunWith(SpringRunner.class)
@SpringBootTest(classes = IntegrationApplication.class,
    webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
@AutoConfigureMockMvc
@ActiveProfiles("test")
public class MyControllerTest {

==================================

@SpringBootApplication
public class IntegrationApplication {

public static void main(String[] args) {
    SpringApplication.run(IntegrationApplication.class, args);
}

【讨论】:

  • 什么是IntegrationApplication? Spring Boot 主类?
  • 是的。此类仅用于测试。还有另一个“真实”的弹簧靴主。您还可以分析您的配置类,例如“@Profile("!test")”以将其从测试上下文中排除。
  • 感谢您的回答。 @Andy Wilkinson 的回答对我有用。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-04-03
  • 2019-08-19
  • 1970-01-01
  • 2015-06-17
  • 2020-12-13
  • 2022-08-04
相关资源
最近更新 更多