Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spring boot unit test not work with application.yml

I'm not able to make my unit test to read application.yml. I have followed the answer as the url below but it's still not working.

Spring Boot properties in 'application.yml' not loading from JUnit Test

Appreciate if somebody can help. Thanks.

My code as below:

Application.java

@SpringBootApplication
@ImportResource("classpath:app-config.xml")
public class Application {

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

TestTokenGenerator.java

    @RunWith(SpringJUnit4ClassRunner.class)
    @SpringApplicationConfiguration(classes=Application.class, initializers=ConfigFileApplicationContextInitializer.class)
    @ContextConfiguration(locations={"classpath:app-config-test.xml"})
    public class TestTokenGenerator {

        private static final Logger log = LoggerFactory.getLogger(TestTokenGenerator.class);

        @Value("${test}")
        private String testB;

        @Test
        public void testGenerate() throws UnrecoverableKeyException, KeyStoreException, NoSuchAlgorithmException, CertificateException, IOException{
            log.info(testB);
            log.info(tokenGenerator.generateToken());
}

application.yml

test: "123123"
like image 276
A1ucard Avatar asked May 31 '26 14:05

A1ucard


1 Answers

See the comments for this issue https://github.com/spring-projects/spring-boot/issues/603, for example.

Declaring both @ContextConfiguration and @SpringApplicationConfiguration directly on a test class is not supported. The first instance of @ContextConfiguration that is discovered for a given test class (either on a class in the test class hierarchy or as a meta-annotation) will be used. All others will be ignored.

like image 170
jny Avatar answered Jun 02 '26 02:06

jny