在以下集成测试中,Spring Boot无法找到正确的属性文件并读取其值:
@RunWith(SpringRunner.class)
@SpringBootTest()
@ActiveProfiles("embedded")
public class ApiApplicationTests {
@Autowired
protected Environment env;
@Test
public void contextLoads() {
}
@Test
public void verifyProperty() {
assertEquals("jdbc:h2:mem:testdb",
env.getProperty("spring.datasource.url"));
}
}
基于它选择属性文件application-embedded.yml:
spring:
h2:
console:
enabled: true
liquibase:
enabled: true
change-log: classpath:db/changelog/db.changelog-master.xml
drop-first: true # should be false in prod but good for dev and test!
datasource:
url: jdbc:h2:mem:testdb
username: h2
password: h2
security:
oauth2:
resource:
filter-order: 3
signing-key: MaYzkSjmkzPC57L
security-realm: AvMaint Realm
jwt:
client-id: avmaintwebsitejwtclientid
client-secret: XY7kmzoNzl100
grant-type: password
scope-read: read
scope-write: write
resource-ids: avmaintwebsitejwtresourceid
此测试失败:“java.lang.IllegalStateException:未找到必需的键'url'”。这表示应用程序似乎看到了配置文件:
2018-05-20 10:42:36.810 INFO 66697 --- [ Test worker] au.com.avmaint.api.ApiApplicationTests : The following profiles are active: embedded
看起来,在找到配置文件之后,它就会继续并且无论如何都会读取“默认”值。
谁知道为什么?另外,我发现通过添加注释
@TestPropertySource("/application-embedded.yml")
我可以强制它使用该文件,但那么配置文件的重点是什么?
答案 0 :(得分:0)
您可以使用@SpringBootTest(classes = YourMainApplicationClassName.class)。希望这有助于将主类加载为入口点,并且还将自行选择所有相关配置(即,使用所有配置加载应用程序上下文)