我正在设置 spring boot 应用程序,我希望使用自定义文件名而不是 application.yml 进行配置。原因是运行这些应用程序的服务器端 tomcat。
我定义了应用类:
@SpringBootApplication(scanBasePackages={"com.example"})
public class Application extends SpringBootServletInitializer {
public static void main(String[] args) {
System.setProperty("spring.config.name", "myapp");
SpringApplication.run(Application.class, args);
}
@Override
protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {
return application.properties("spring.config.name: myapp").sources(Application.class);
}
...
配置名为myapp.yml
在 JUnit 测试中,我有以下注释:
@RunWith(SpringRunner.class)
@SpringBootTest(classes = {Application.class})
@ContextConfiguration(initializers = {ConfigFileApplicationContextInitializer.class})
@AutoConfigureMockMvc
public class UserTest {
...
和 junit 的 pom 依赖:
<dependency>
<groupId>org.jmockit</groupId>
<artifactId>jmockit</artifactId>
<version>1.31</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.powermock</groupId>
<artifactId>powermock-module-junit4</artifactId>
<version>1.7.3</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.powermock</groupId>
<artifactId>powermock-api-mockito</artifactId>
<version>1.7.3</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<version>1.5.3.RELEASE</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-test</artifactId>
<version>RELEASE</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework.restdocs</groupId>
<artifactId>spring-restdocs-mockmvc</artifactId>
<version>RELEASE</version>
<scope>test</scope>
</dependency>
<!-- if I remove this dependency then normal application works with custom name but if I have it in dependencies then mvn spring-boot:run does not find configuration either -->
<dependency>
<groupId>org.yaml</groupId>
<artifactId>snakeyaml</artifactId>
<version>RELEASE</version>
<scope>test</scope>
</dependency>
我尝试了很多不同的东西,但我无法让它按照我想要的方式工作。我想要自己的配置文件名,然后用@ActiveProfiles注解解决不同的配置。谢谢!
最佳答案
正如@M.Deinum 提到的,您应该在测试类的@BeforeClass 方法中初始化属性:
@BeforeClass
public static void initProperties() {
System.setProperty("spring.config.name", "myapp");
}
好的做法是在测试后整理属性,这样其他测试就不会受到这些属性的影响
@AfterClass
public static void clearProperties() {
System.clearProperty("spring.config.name");
}
但是有更好的选择来使用测试属性:
您也应该在测试中使用 application.yaml。您的动态配置(例如数据库凭据)不应放在此配置文件中。它们应该通过 env 属性传递给应用程序(因此 12 factor app principles )。
在测试期间,有多种方法可以定义此动态配置。例如:
- 利用上述机制
@BeforeClass
+System.setPROperty
- 或者您可以通过
@TestProperties
注释或SpringBootTest.properties
属性使用额外的测试配置文件
关于java - Spring Boot 1.5+ junit 测试不加载具有自定义名称的配置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50639465/