我希望我的主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
}
我在这里想念什么?
答案 0 :(得分:0)
我的情况与所问问题完全相同,并且存在相同的错误。这对我有用。
您可以将以下内容添加到src / test / resources / application.properties中,以便在测试期间不会进行jndi查找-
spring.autoconfigure.exclude=org.springframework.boot.autoconfigure.jdbc.JndiDataSourceAutoConfiguration