Java Spring Boot Test: How to exclude java configuration class from test context

前端 未结 5 813
后悔当初
后悔当初 2021-01-17 07:41

I have a Java web app with spring boot

When run test I need to exclude some Java config files:

Test config (need to include when test run):

@         


        
5条回答
  •  孤独总比滥情好
    2021-01-17 08:13

    Typically you would use Spring profiles to either include or exclude Spring beans, depending on which profile is active. In your situation you could define a production profile, which could be enabled by default; and a test profile. In your production config class you would specify the production profile:

    @Configuration
    @PropertySource("classpath:otp.properties")
    @Profile({ "production" })
    public class OTPConfig {
    }
    

    The test config class would specify the test profile:

    @TestConfiguration
    @Import({ TestDataSourceConfig.class, TestMailConfiguration.class,    TestOTPConfig.class })
    @TestPropertySource("classpath:amc-test.properties")
    @Profile({ "test" })
    public class TestAMCApplicationConfig extends AMCApplicationConfig {
    }
    

    Then, in your test class you should be able to say which profiles are active:

    @RunWith(SpringRunner.class)
    @SpringBootTest(classes = TestAMCApplicationConfig.class)
    @ActiveProfiles({ "test" })
    public class AuthUserServiceTest {
      ....
    }
    

    When you run your project in production you would include "production" as a default active profile, by setting an environment variable:

    JAVA_OPTS="-Dspring.profiles.active=production"
    

    Of course your production startup script might use something else besides JAVA_OPTS to set the Java environment variables, but somehow you should set spring.profiles.active.

提交回复
热议问题