unit-testing - Spring 引导配置文件。如何测试?

标签 unit-testing 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"));
}

我的第一个测试执行正常,但其他测试失败。

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/

相关文章:

unit-testing - TestBed configureTestingModule 在一个模块中定义所有 spec.ts 通用的导入、声明、提供程序和管道 - 模式

testing - 如何减少/减少 Blackberry Simulator 的应用程序存储和内置内存存储?

java - 获取所有路径变量

javascript - 未找到使用 grunt 运行 jest 的测试

java - 您将如何测试静态方法 URLEncoder.encode?

testing - 基于 leiningen 测试元数据的 log4j 属性文件?

java - Spring MVC 和 @RequestParam 与 x-www-form-urlencoded

java - tomcat-embed-core 8.5.4 上缺少 AbstractServletInputStream

Scala:Mock init 因 Cats IO 类型参数而失败

testing - Chrome DevTools > Service Workers > Testing > Local dev environment serves via http on a LAN