【问题标题】:Unit Test class that uses only local variables for composition仅使用局部变量进行组合的单元测试类
【发布时间】:2017-10-16 09:48:35
【问题描述】:

我正在编写使用具有非常相似属性的各种 REST api 端点的应用程序。唯一的区别在于端点地址和有效负载。标题、方法和其他内容保持不变。这就是为什么我创建了与我的远程主机通信的类,它被称为RestApiCommunicator,它具有方法generateRequestAndCallEndpoint(List payload),它将有效负载与执行休息调用所需的所有必需的东西一起包装。 比,我有各种类,它们只用适当的端点后缀和它的资源来调用这个通信器类。 一切正常,但我想对所有这些类进行单元测试。我试图通过阅读很多 SO 问题来弄清楚如何做到这一点,但它们是相当复杂的案例,我的很简单。 我试图找出一种正确的方法来对一个看起来像这样的类进行单元测试:

class MyRestClient {

    public void useRestApi(List<MyResources> myResources) {
        RestApiCommunicator restApiCommunicator = new RestApiCommunicator ("/some/endpoint");
        restApiCommunicator.generateRequestAndCallEndpoint(myResources);
    }
}

我想测试是否使用正确的端点地址创建了通信器,以及是否使用我的示例有效负载准确地调用了一次 generateRequestAndCallEndpoint

我唯一想到的就是将restApiCommunicator 设为一个字段,为该字段创建setter 并在单元测试中模拟它。但这在我看来是相当肮脏的解决方案,我不想修改我的代码以允许测试。

也许你可以指出我可以使用一些好的模式测试这个类的方向。

(ps。如果这很重要 - 这是一个 Spring Boot 应用程序)

【问题讨论】:

    标签: java spring unit-testing mocking


    【解决方案1】:

    你可以为通讯器提供一个工厂

    class MyRestClient {
        private RestApiCommunicatorFactory factory = ...
    
        public void useRestApi(List<MyResources> myResources) {
            factory.getCommunicator("/some/endpoint")
                .generateRequestAndCallEndpoint(myResources);
        }
    

    在您的单元测试中,您提供了一个工厂模拟,它返回模拟通信器。具体的语言取决于您选择的模拟库。

    【讨论】:

      【解决方案2】:

      完全按照您的要求进行操作的一种方法(即“测试是否使用正确的端点地址创建了通信器,以及是否使用我的示例有效负载只调用了一次 generateRequestAndCallEndpoint”)是使用 JMockit 模拟它:

      public final class MyRestClientTest {
          @Tested MyRestClient restClient;
          @Mocked RestApiCommunicator restApi;
      
          @Test
          public void verifyUseOfRestApi() {
              List<MyResource> resources = asList(new MyResource("a"), new MyResource("b"));
      
              restClient.useRestApi(resources);
      
              new Verifications() {{
                  new RestApiCommunicator("/some/endpoint");
                  restApi.generateRequestAndCallEndpoint(resources); times = 1;
              }};
          }
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-10-24
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-11-29
        相关资源
        最近更新 更多