我有一个小型 Spring Boot 应用程序,在“/health”处定义了一个健康端点。这是在代码中定义的:
@Component
public class MyHealthEndpoint implements HealthIndicator {
public Health health() {
# ...
# returns health info as JSON here
# ...
}
}
因此,在运行应用程序时,访问位于 localhost/health 的端点会返回一些应用程序健康信息。
我的问题是:最好的测试方法是什么?
我想对 MyHealthEndpoint 类进行单元测试,我尝试在我的测试类中使用 @Autowired 对其进行实例化,但这不起作用。 还尝试在测试类中实例化它
MyHealthEndpoint testHealthEndpoint = new MyHealthEndpoint();
但这只是返回一个没有健康信息的空新类,所以显然 Spring Boot 中的依赖注入(inject)/IOC 没有注册它,或者我只是 Spring 的新手不知道如何去做正确。
运行集成测试的唯一解决方案是启动应用程序并直接对端点运行测试 http GET 调用,然后断言返回的 JSON 还是您有更好的想法?
最佳答案
您应该使用 Sprint 测试上下文框架 检查这个: http://docs.spring.io/spring/docs/current/spring-framework-reference/html/testing.html#integration-testing-annotations
您可以在这里找到库:https://mvnrepository.com/artifact/org.springframework/spring-test
您应该使用 @ContextConfiguration 注释测试类(或父类),您可以设置您的配置 xml(位置参数)和配置 Java 类(类参数) 如果你使用 SpringMVC,也添加 @WebAppConfiguration 注释
如果已配置,您可以在测试中使用@Autowired。
关于java - 单元测试 Spring Boot 应用程序端点,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27860928/