如何测试我的配置文件?
这是我的测试
@Test
public void testDevProfile() throws Exception {
System.setProperty("spring.profiles.active", "dev");
Application.main(new String[0]);
String output = this.outputCapture.toString();
Assert.assertTrue(output.contains("The following profiles are active: dev"));
}
@Test
public void testUatProfile() throws Exception {
System.setProperty("spring.profiles.active", "uat");
Application.main(new String[0]);
String output = this.outputCapture.toString();
Assert.assertTrue(output.contains("The following profiles are active: uat"));
}
@Test
public void testPrdProfile() throws Exception {
System.setProperty("spring.profiles.active", "prd");
Application.main(new String[0]);
String output = this.outputCapture.toString();
Assert.assertFalse(output.contains("The following profiles are active: uat"));
Assert.assertFalse(output.contains("The following profiles are active: dev"));
Assert.assertFalse(output.contains("The following profiles are active: default"));
}
我的第一个测试执行正常,但其他测试失败。
org.springframework.jmx.export.UnableToRegisterMBeanException: Unable to register MBean [org.springframework.boot.actuate.endpoint.jmx.DataEndpointMBean@6cbe68e9] with key 'requestMappingEndpoint'; nested exception is javax.management.InstanceAlreadyExistsException: org.springframework.boot:type=Endpoint,name=requestMappingEndpoint
如何在下一次测试开始前停止实例?或者哪种方法更好?
谢谢
最佳答案
我会这样做:
@RunWith(SpringJUnit4ClassRunner.class)
@SpringApplicationConfiguration(classes = SpringBootApp.class)
@ActiveProfiles("dev")
public class ProfileDevTest {
@Value("${someProperty}")
private String someProperty;
@Test
public void testProperty() {
assertEquals("dev-value", someProperty);
}
}
上面的代码假设你有一个像这样的application-dev.properties
:
someProperty=dev-value
我将为您希望测试的每个配置文件进行一个测试 class,上面的这个是针对配置文件 dev 的。如果您必须对事件配置文件(而不是属性)进行测试,您可以这样做:
@Autowired
private Environment environment;
@Test
public void testActiveProfiles() {
assertArrayEquals(new String[]{"dev"}, environment.getActiveProfiles());
}
关于unit-testing - Spring 引导配置文件。如何测试?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38834267/