Spring Boot: как отключить поиск JNDI и использовать взамен spring.datasource для тестирования? - PullRequest
0 голосов
/ 20 октября 2018

Мне бы хотелось, чтобы мое основное приложение Spring Boot конфигурировало мой источник данных, используя JNDI через

spring.datasource.jndi-name=java:jboss/datasources/MyAppDS

в моем application.properties файле.

В то же время я хотел бы использовать другие настройки источника данных, чтобы иметь возможность запускать мои тестовые случаи с использованием источника данных в памяти (т. Е. H2).Я создал отдельный application.properties файл в src/test/resources, и в нем есть следующее:

spring.datasource.driver-class-name=org.h2.Driver
spring.datasource.url=jdbc:h2:mem:db;DB_CLOSE_DELAY=-1
spring.datasource.username=sa
spring.datasource.password=sa

Однако тестовые файлы не выглядят так, и я получаю следующую ошибку:

[main] WARN  o.s.w.c.s.GenericWebApplicationContext - Exception encountered during context initialization - cancelling refresh attempt: org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'org.springframework.boot.autoconfigure.orm.jpa.HibernateJpaAutoConfiguration': Unsatisfied dependency expressed through constructor parameter 0; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'dataSource' defined in class path resource [org/springframework/boot/autoconfigure/jdbc/JndiDataSourceAutoConfiguration.class]: Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [javax.sql.DataSource]: Factory method 'dataSource' threw exception; nested exception is org.springframework.jdbc.datasource.lookup.DataSourceLookupFailureException: Failed to look up JNDI DataSource with name 'java:jboss/datasources/MyAppDS'; nested exception is javax.naming.NoInitialContextException: Need to specify class name in environment or system property, or as an applet parameter, or in an application resource file:  java.naming.factory.initial

, что приводит к сбою моих тестов.

То, что я сделал:

Переименовал мой файл свойств в testapplication.properties в src/test/resources и обновил содержимое с помощью

spring.mydatasource.driver-class-name=org.h2.Driver
spring.mydatasource.url=jdbc:h2:mem:db;DB_CLOSE_DELAY=-1
spring.mydatasource.username=sa
spring.mydatasource.password=sa

и добавление в мой тестовый класс следующих аннотаций:

@RunWith(SpringRunner.class)
@WebAppConfiguration("classpath:META-INF/web-resources")
@TestPropertySource(locations="classpath:testapplication.properties")
@ConfigurationProperties(prefix="spring.mydatasource")
public class BrandsSvcTests {

    private MockMvc mockMvc;

    @Autowired
    private WebApplicationContext wac;  

    @Before
    public void setup() throws Exception {
         this.mockMvc = MockMvcBuilders.webAppContextSetup(wac).build();
    }

      // ... my test cases
}

Что мне здесь не хватает?

...