【问题标题】:How to test for exception in Nest?如何在 Nest 中测试异常?
【发布时间】:2018-11-10 09:08:15
【问题描述】:

当 Nest 在 IGetResponse.OriginalException 属性中具有值时,我正在尝试测试某些异常的结果。

我首先设置了响应:

var response = A.Fake<Nest.IGetResponse<Dictionary<string, object>>>();
A.CallTo(() => response.OriginalException).Returns(new Exception("Status code 404"));

然后是假弹性客户端:

var client = A.Fake<Nest.IElasticClient>();
A.CallTo(client)
    .WithReturnType<Nest.IGetResponse<Dictionary<string, object>>>()
    .Returns(response);

客户端被注入到我正在测试的类中。

但是,在单步执行代码时,调用客户端时会返回伪造的响应,但 OriginalException getter 没有任何价值。它不为空,但所有属性都没有任何值。我期待 OriginalException.Message 等于 状态码 404

我也尝试将响应对象设置为:

var response = A.Fake<Nest.IGetResponse<Dictionary<string, object>>>();
A.CallTo(() => response.OriginalException.Message).Returns("Status code 404");

...同样糟糕的结果。

如何设置IGetResponse,以便我可以在正在测试的课程中评估OriginalException.Message

请求了更多代码。我可以展示整个测试,我会展示正在测试的方法。这是我的整个测试:

    [TestMethod]
    [ExpectedException(typeof(NotFoundException))]
    public void Get_ClientReturns404_ThrowsNotFoundException()
    {
        // setup
        var request = new DataGetRequest
        {
            CollectionName = string.Empty,
            DocumentType = string.Empty,
            DataAccessType = string.Empty
        };

        var response = A.Fake<Nest.IGetResponse<Dictionary<string, object>>>();
        A.CallTo(() => response.OriginalException.Message).Returns("Status code 404");

        var client = A.Fake<Nest.IElasticClient>();
        A.CallTo(client)
            .WithReturnType<Nest.IGetResponse<Dictionary<string, object>>>()
            .Returns(response);

        var elasticSearch = new ElasticSearch(null, client);

        // test
        var result = elasticSearch.Get(request);

        // assert
        Assert.Fail("Should have hit an exception.");
    }
}

这是正在测试的方法:

    public async Task<Dictionary<string, object>> Get(DataGetRequest getRequest)
    {
        GetRequest request = new GetRequest(getRequest.CollectionName, getRequest.DocumentType, getRequest.Id);
        var response = await Client.GetAsync<Dictionary<string, object>>(request);

        if (response.OriginalException != null)
        {
            var message = response.OriginalException.Message;
            if (message.Contains("Status code 404"))
                throw new NotFoundException(String.Format("Not Found for id {0}", getRequest.Id));
            else
                throw new Exception(message);
        }                

        return response.Source;
    }

IF 块中的错误处理不是很健壮。一旦单元测试成功,那么代码可能会受到更多的喜爱。

【问题讨论】:

  • 什么都没有出现。你能粘贴更多代码吗?理想情况下是一个可运行的测试,但至少你如何将客户端注入到你正在测试的类中,你如何调用那个类,以及被调用的方法是做什么的?
  • @BlairConrad 完成。不知道会有多大帮助,但你永远不知道。

标签: c# mstest nest fakeiteasy


【解决方案1】:

模拟客户端的返回类型错误,因为IElasticClient.GetAsync&lt;&gt; 返回Task&lt;IGetResponse&lt;T&gt;&gt;

Task<IGetResponse<T>> GetAsync<T>(IGetRequest request, CancellationToken cancellationToken = default(CancellationToken)) where T : class;

Source

所以设置需要返回一个Task派生结果来允许异步代码

var response = await Client.GetAsync<Dictionary<string, object>>(request);

按预期流动。

例如

[TestMethod]
[ExpectedException(typeof(NotFoundException))]
public async Task Get_ClientReturns404_ThrowsNotFoundException() {

    //Arrange
    var originalException = new Exception("Status code 404");

    var response = A.Fake<Nest.IGetResponse<Dictionary<string, object>>>();
    A.CallTo(() => response.OriginalException).Returns(originalException);

    var client = A.Fake<Nest.IElasticClient>();
    A.CallTo(() => 
        client.GetAsync<Dictionary<string, object>>(A<IGetRequest>._, A<CancellationToken>._)
    ).Returns(Task.FromResult(response));

    var request = new DataGetRequest {
        CollectionName = string.Empty,
        DocumentType = string.Empty,
        DataAccessType = string.Empty
    };

    var elasticSearch = new ElasticSearch(null, client);

    // Act
    var result = await elasticSearch.Get(request);

    // Assert
    Assert.Fail("Should have hit an exception.");
}

【讨论】:

  • 不错。直接伪造GetAsync 而不是使用强大但可能容易出错的WithReturnType 语法,可以获得+1 奖励。
猜你喜欢
  • 2020-10-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-01-23
  • 1970-01-01
  • 2011-01-22
  • 2018-07-20
  • 2017-06-18
相关资源
最近更新 更多