【问题标题】:Unit testing Spring Boot application endpoints单元测试 Spring Boot 应用程序端点
【发布时间】:2015-01-09 12:47:31
【问题描述】:

我有一个小型 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 中的依赖注入/IOC 没有注册它,或者我只是 Spring 的新手,不知道该怎么做正确。

是通过启动应用程序并直接对端点运行测试 http GET 调用然后断言返回的 JSON 来运行集成测试的唯一解决方案,还是您有更好的想法?

【问题讨论】:

    标签: java spring unit-testing


    【解决方案1】:

    您应该使用 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(locations 参数)和配置 Java 类(classes 参数) 如果你使用 SpringMVC 也添加 @WebAppConfiguration 注解

    如果已配置,您可以在测试中使用@Autowired。

    【讨论】:

    • 同时我开始使用 Spring MVC 测试框架 spring.io/blog/2012/11/12/…,我认为这是测试基于 Spring 的 REST 端点的正确解决方案
    猜你喜欢
    • 2017-01-30
    • 2019-01-24
    • 2016-10-12
    • 2015-05-17
    • 2016-04-23
    • 2019-05-18
    • 2019-11-01
    • 2016-05-28
    相关资源
    最近更新 更多