简体   繁体   English

Spring引导测试配置未被选中

[英]Spring boot test configuration not being picked

I am writing an integration test for my application, and want to use a custom webmvc configuration for my tests 我正在为我的应用程序编写集成测试,并希望为我的测试使用自定义webmvc配置

I have three classes in my base package com.marco.nutri: 我的基础包com.marco.nutri中有三个类:

  • Application(which is annotated with @SpringBootApplication) 应用程序(使用@SpringBootApplication注释)
  • MvcConfig(@Configuration and @EnableWebMVC) MvcConfig(@Configuration和@EnableWebMVC)
  • SecurityConfig(@Configuration and @EnableWebSecurity) SecurityConfig(@Configuration和@EnableWebSecurity)

My test is in the package br.com.marco.nutri.integration.auth: 我的测试是在包br.com.marco.nutri.integration.auth中:

@RunWith(SpringRunner.class)
@SpringBootTest(classes={Application.class, WebMvcTestConfiguration.class, SecurityConfig.class})
public class ITSignup {

    //Test code

}

I have a test config class in the package com.marco.nutri.integration: 我在com.marco.nutri.integration包中有一个测试配置类:

@TestConfiguration
@EnableWebMvc
public class WebMvcTestConfiguration extends WebMvcConfigurerAdapter {
    //Some configuration
}

But when I run my test, the MvcConfig.class is picked instead of WebMvcTestConfiguration.class 但是当我运行我的测试时,将选择MvcConfig.class而不是WebMvcTestConfiguration.class

What am I doing wrong? 我究竟做错了什么?

you can annotate your test configuration with @Profile("test") and your real one with @Profile("production") 您可以使用@Profile("test")注释您的测试配置,使用@Profile("production")注释您的测试配置

and in your properties file put the property spring.profiles.active=production and in your test class put @Profile("test") . 并在您的属性文件中放置属性spring.profiles.active=production并在您的测试类中放置@Profile("test") So when your application starts it will use "production" class and when test stars it will use "test" class. 因此,当您的应用程序启动时,它将使用“生产”类,当测试星星时它将使用“测试”类。

from documentation 来自文档

Unlike regular @Configuration classes the use of @TestConfiguration does not prevent auto-detection of @SpringBootConfiguration. 与常规@Configuration类不同,使用@TestConfiguration不会阻止自动检测@SpringBootConfiguration。

Unlike a nested @Configuration class which would be used instead of a your application's primary configuration, a nested @TestConfiguration class will be used in addition to your application's primary configuration. 与嵌套的@Configuration类不同,它将用于代替应用程序的主要配置,除了应用程序的主要配置之外,还将使用嵌套的@TestConfiguration类。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM