Spring Boot with datasource when testing

前端 未结 1 1411
长发绾君心
长发绾君心 2020-12-17 17:56

I am using Spring Boot application and the auto cofiguration is enabled. The main Application file is marked as @EnableAutoConfiguration. The datasource is look

相关标签:
1条回答
  • 2020-12-17 18:45

    2) Is there a way to exclude the datasource configuration class from being called when executing test case ?

    You can add a application.properties config file into your src/test/resources and spring boot would pick those configurations in test environments. I suppose, you have application.properties in your src/main/resources like this:

    spring.datasource.jndi-name=some_jndi
    

    This JNDI resource will be used in your production environment. For your test environment you can use a, say MySQL database, by adding these configurations into your test application.properties:

    spring.datasource.url=jdbc:mysql://localhost/test
    spring.datasource.username=dbuser
    spring.datasource.password=dbpass
    spring.datasource.driver-class-name=com.mysql.jdbc.Driver
    

    3) Should I create an embedded server so that the JNDI lookup can be done when executing test case ?

    As i said, you can totally bypass the fact that you're using JNDI for production by adding test specific configurations.

    1) How do we generally deal with datasource (when looking up from JNDI) in spring boot application for testing ?

    You can mock JNDI resources using facilities available in org.springframework.mock.jndi package. For example by using SimpleNamingContextBuilder you can:

    SimpleNamingContextBuilder builder = new SimpleNamingContextBuilder();
    builder.bind("jndi_name", dataSource);
    builder.activate();
    

    The other option is, of course, using Non JNDI resources in test environments.

    0 讨论(0)
提交回复
热议问题