簡體   English   中英

將@WebMvcTest 與spring-boot 一起使用時如何排除@Configuration 類?

[英]How to exclude a @Configuration class when using @WebMvcTest with spring-boot?

我正在為休息控制器編寫junit。 我只想加載與控制器相關的最小上下文,我認為這就是@WebMvcTest加載上下文的方式。 但是 junit 正在加載完整的 Spring 上下文,並且由於無法創建某些 bean 而失敗。

我已經搜索並閱讀了許多關於 stackoverflow 的問題,但沒有一個解決方案可以排除特定的配置。 為控制器編寫junit時如何加載最小上下文? 或者有什么辦法可以排除一些配置類? 我使用的是 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);
    }
}

您對@ComponentScan使用禁用了@WebMvcTest用於限制通過掃描找到的組件類型的過濾器。

您應該刪除@ComponentScan從主應用程序類,並使用basePackages的屬性@SpringBootApplication代替。

您還應該將@EnableJms@EnableAspectJAutoProxy移動到單獨的@Configuration類,以便在使用@WebMvcTest時不會啟用它們。 或者,您可以完全刪除它們,因為它們被 Spring Boot 的自動配置所覆蓋。

當您的測試類位於 test 文件夾中並使用“test”配置文件運行時,您的真實配置類將被排除在外。 這是我如何配置 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);
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM