java - 单元测试 Spring Boot 应用程序端点

标签 java spring unit-testing

我有一个小型 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/

相关文章:

java - 什么是好的客户端、上传前调整大小、flash/java uploader ?

spring - 使用自己的登录表单进行太多重定向 - Spring Security

java - Spring Web Service REST API JSON 响应始终包含 boolean 值

java - 如何正确使用模拟

asp.net-mvc - 在使用 ASP.Net Identity 的 ASP.Net MVC 注册代码上运行单元测试时出错

java - 将一个简单的查询转换为 hibernate

java - 插入 mongoDB 时发生 MongoInternalException

java - 使用 Java 在 MS Word 文件中创建表格

spring - 使用 Spring 测试在测试中回滚事务

javascript - 如何对 AngularJS 服务/工厂进行单元测试