Java Spring Boot Test: How to Exclude a Java Configuration Class from a Test Context

I have a Java web application with spring boot

When running the test, I need to exclude some Java configuration files:

Test configuration (must be enabled when starting the test):

@TestConfiguration
@PropertySource("classpath:otp-test.properties")
public class TestOTPConfig { }

Production configuration (must be excluded when starting the test):

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

Testing class (with explicit configuration class):

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

Test Configuration:

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

There is also a class:

@SpringBootApplication
public class AMCApplication { }

When a test is used OTPConfig, but I need TestOTPConfig...

How can i do this?

+10
source share
4 answers

Spring Spring beans, , . , ; . :

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

:

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

, :

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

, "" , :

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

, script - , JAVA_OPTS, Java, - spring.profiles.active.

+10

@ConditionalOnProperty, :

@ConditionalOnProperty(value="otpConfig", havingValue="production")
@Configuration
@PropertySource("classpath:otp.properties")
public class OTPConfig { }

:

@ConditionalOnProperty(value="otpConfig", havingValue="test")
@Configuration
@PropertySource("classpath:otp-test.properties")
public class TestOTPConfig { }

main/resources/config/application.yml

otpConfig: production

test/resources/config/application.yml

otpConfig: test
+2

, -

  1. @ConditionalOnProperty .
  2. . . , . , .
  3. application.properties src/test/resources, , .

!

0

@ConditionalOnMissingClass("org.springframework.test.context.junit4.SpringJUnit4ClassRunner") . SpringJUnit4ClassRunner , .

-1

Source: https://habr.com/ru/post/1655985/


All Articles