Spring Boot with data source during testing

I am using the Spring application to download and auto-tuning is enabled. The main application file is marked as @EnableAutoConfiguration . The JNDI data source is configured using java config, and the class that creates the data source is marked as @Configuration .

I have a test class as shown below.

 @RunWith( SpringJUnit4ClassRunner.class ) @WebAppConfiguration @ContextConfiguration( classes = Application.class ) public class TestSomeBusiness {} 

The problem is that when I run the test case, it searches for datasource jndi, which does not work, because the test case does not work inside the server environment. As far as I know, the classes in the classpath marked with @Configuration are executing and that the reason causes the data source to be searched.

The work I found, instead of searching, JNDI creates the data source using DriverManagerDataSource , so even if its not a server environment, the search for the data source will not fail.

My questions:

1) How do we usually deal with a data source (when searching with JNDI) in a spring boot application for testing?

2) Is there a way to exclude the data source configuration class when invoked when running a test case?

3) Should I create an embedded server so that the JNDI search can be performed while running the test case?

+7
java spring spring-boot
source share
1 answer

2) Is there a way to exclude the data source configuration class when invoked when running a test case?

In the src/test/resources and spring configuration, you can add the application.properties configuration file to select these 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 a test environment, you can use, say, a MySQL database by adding these configurations to your application.properties test:

 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 performed while running the test case?

As I said, you can completely circumvent the fact that you use JNDI for production by adding test configurations.

1) How do we usually deal with a data source (when viewing JNDI) in a spring boot application for testing?

You can mock JNDI resources using the tools available in the org.springframework.mock.jndi package. For example, using SimpleNamingContextBuilder , you can:

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

Another option, of course, uses Non JNDI resources in test environments.

+6
source share

All Articles