![](/img/trans.png)
[英]Override @PropertySource with @TestPropertySource in Spring Boot
[英]Spring Boot `TestPropertySource` not Working
我有一个简单的单元测试,我希望单元测试加载我放在src/test/resources/test.properties
中的测试属性文件,而不是src/main/resources/application.properties
中的属性文件src/main/resources/application.properties
。
我的测试class设置如下:
@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
@AutoConfigureMockMvc
@TestPropertySource(locations = "classpath:src/test/resources/properties-test.yml")
public class SecurityConfigurationTest {
@MockBean
KafkaConfiguration kafkaConfiguration;
@MockBean
KafkaMonitor kafkaMonitor;
@MockBean
BuildProperties buildProperties;
@Autowired
MockMvc mockMvc;
@Test
public void unauthorizedUser_shouldNotAccessHomePage() throws Exception{
mockMvc
.perform(get("/"))
.andExpect(status().isUnauthorized());
}
}
但是我收到以下错误,提示我没有正确指定此属性文件:
Caused by: java.io.FileNotFoundException: class path resource [src/test/resources/test.properties] cannot be opened because it does not exist
我怎样才能设法让我的单元测试使用test.properties
文件而不是application.properties
文件?
在 pom.xml 中添加一个profiles 标签,指定程序在运行时应该选择哪个属性文件。
<profiles>
<profile>
<id>test</id>
<properties>
<activatedProperties>test</activatedProperties>
</properties>
<activation>
<activeByDefault>true</activeByDefault>
</activation>
</profile>
</profiles>
注意:您的属性文件的名称必须是application-test.properties 。
这将使您的测试属性处于活动状态,但要访问它,您需要配置测试资源文件夹并让 intellij 知道“在运行时使用它”。
在 Intellij 中,您可以更改用于运行项目的资源文件夹,因此您需要......
这意味着为运行测试资源文件夹创建了一个新的运行配置。
Maven 默认会将 package src/test/resources/
文件夹下的所有文件放到类路径下。 所以要通过类路径引用它,它应该是:
@TestPropertySource(locations = "classpath:test.properties")
或者,如果你想通过系统文件路径引用它,你可以将其更改为:
@TestPropertySource(locations = "file:src/test/resources/test.properties")
在幕后,它使用ResourceLoader
来加载文件。 有关更多详细信息,请参阅此内容。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.