Mar*_*lin 1 testing unit-testing spring-boot
如何测试我的个人资料?
那是我的考验
@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"));
}
Run Code Online (Sandbox Code Playgroud)
我的第一个测试执行正常,但其他测试失败。
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
Run Code Online (Sandbox Code Playgroud)
如何在下一次测试开始之前停止实例?还是哪种方法更好?
谢谢
我会这样:
@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);
}
}
Run Code Online (Sandbox Code Playgroud)
上面的代码假定您具有application-dev.properties这样的代码:
someProperty=dev-value
Run Code Online (Sandbox Code Playgroud)
对于您要测试的配置文件,我将有一个测试类,以上这是针对profile dev的。如果必须对活动概要文件(而不是属性)进行测试,则可以执行以下操作:
@Autowired
private Environment environment;
@Test
public void testActiveProfiles() {
assertArrayEquals(new String[]{"dev"}, environment.getActiveProfiles());
}
Run Code Online (Sandbox Code Playgroud)