[英]Override application.properties for integration tests in spring-boot app
I have a standard spring-boot
app and I want to use MS SQL database for the production environment, whereas for integration tests I'd like to use h2
databse. 我有一个标准的spring-boot
应用程序,我想在生产环境中使用MS SQL数据库,而对于集成测试,我想使用h2
databse。 The problem is that I wasn't able to find out, how to override the default application.properties
file. 问题是我无法找出如何覆盖默认的application.properties
文件。 Even though I was trying to follow some tutorials, I didn't come up with the right solution...maybe I'm just missing something... 即使我尝试遵循一些教程,也没有提出正确的解决方案……也许我只是缺少了一些东西……
The main class: 主班:
@SpringBootApplication
@EnableTransactionManagement
public class MyApplication {
public static void main(String[] args) {
SpringApplication.run(MyApplication .class, args);
}
}
and the class with tests: 和带有测试的类:
@RunWith(SpringJUnit4ClassRunner.class)
@SpringApplicationConfiguration(classes = MyApplication.class)
@WebIntegrationTest
public class MessageControllerTest {
@Autowired
MessageRepository messageRepository;
...
...
...
@Test
public void testSomething(){
...
...
...
...
}
}
So the question is, how to force the spring-boot to use application-test.properties
file when running the tests, instead of application.properties
, which should be used during the run time. 因此,问题是,如何在运行测试时强制spring-boot使用application-test.properties
文件,而不是应在运行时使用application.properties
。
I tried for example to replace @WebIntegrationTest
annotation with @TestPropertySource(locations="classpath:application-test.properties")
, but this results in java.lang.IllegalStateException: Failed to load ApplicationContext
. 我尝试例如用@TestPropertySource(locations="classpath:application-test.properties")
替换@WebIntegrationTest
批注,但这导致java.lang.IllegalStateException: Failed to load ApplicationContext
。
Assuming you have a application-test.properties file in your app. 假设您的应用程序中有一个application-test.properties文件。
I do it in two ways : 我有两种方式:
1.CLI JVM Args 1.CLI JVM精简版
mvn spring-boot:run -Drun.jvmArguments="-Dspring.profiles.active=test
add the spring.profiles.active=test
in the application.properties and it will load your application-test.properties file. 在spring.profiles.active=test
添加spring.profiles.active=test
,它将加载您的application-test.properties文件。
@ActiveProfiles("test")
正如您在答案中所指出的那样,用特定的活动配置文件注释类测试(我认为这不适用于拥有大型测试类的情况) @ActiveProfiles("test")
Actually it was pretty easy...after several hours of trying, I've realized that I just needed to annotate my test class with @ActiveProfiles("test")
annotation. 实际上,这很容易...经过几个小时的尝试,我意识到我只需要使用@ActiveProfiles("test")
批注来批注测试类。
@ActiveProfiles("test")
@RunWith(SpringJUnit4ClassRunner.class)
@SpringApplicationConfiguration(classes = MyApplication.class)
@WebIntegrationTest
public class MessageControllerTest {
@Autowired
MessageRepository messageRepository;
...
...
...
@Test
public void testSomething(){
...
...
...
...
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.