首页 > 解决方案 > 为使用 RestClient 的实用程序编写单元测试

问题描述

我们决定创建一个可以跨多个项目重用的 HTTP 记录器,我们创建了一个如下所示的实用程序。

// pseudo-code
public class HttpLog{
      private readonly string uri;
      private readonly RestClient client;

      public HttpLog(string uri){
          this.uri = uri;
          // notice the initialization of rest client
          this.client = new RestClient();
      }

     void write(object data){
         this.client.uri = this.uri + endpoint;
         this.client.postAsync(data);
     }           
}

消费者应该提供 URI,我们已经公开了公共写入方法来记录数据,但是,我们无法对我们的HttpLog类进行单元测试,因为它初始化了其余客户端。我们没有使用依赖注入,因为我们正在创建实用程序。

任何有关如何重构或单元测试的帮助将不胜感激。write()方法。

我们可以想到两种方法

请让我们知道是否有更好的方法来对此代码进行单元测试。

下面的答案说明使用构造函数重载或将属性公开

为什么我不喜欢依赖注入或构造函数重载,因为我坚信消费者/客户端不应该关心或担心实现细节。它们应该尽可能抽象。如果你让它们在构造函数重载中,那么你正在制造一种污染抽象的方法。

例如,如果您使用的是 RestClient 或 HttpClient,他们不会要求您提供有关如何写入数据的 HTTP 实现,他们只是要求您发布 URI 和数据,这对最终用户来说是真正的抽象。

请纠正我如果我的假设是错误的

标签: c#unit-testingrestsharp

解决方案


我们没有使用依赖注入,因为我们正在创建实用程序。

这不是一个原因。如果您使用依赖项并希望能够正确测试它,则应使用依赖项注入。这并不意味着您不能为普通用户提供默认实现。

提供构造函数重载。我不知道你为什么认为这会“低效”。

例子:

public class HttpLog{
      private readonly string uri;
      private readonly RestClient client;

      public HttpLog(string uri) : this(uri, new RestClient()){
      }

      public HttpLog(string uri, RestClient restClient){
          this.uri = uri;
          // notice the initialization of rest client
          this.client = restClient;
      }

     void write(object data){
         this.client.uri = this.uri + endpoint;
         this.client.postAsync(data);
     }           
}

推荐阅读