c# - 如何使用 Moq 为异步函数抛出异常

标签 c# unit-testing .net-core moq xunit

我正在使用 xUnit 和 Moq 编写测试用例。

我在测试类中使用下面的代码来测试另一个类方法的catch()

private readonly  IADLS_Operations _iADLS_Operations;

[Fact]
public void CreateCSVFile_Failure()
{
    var dtData = new DataTable();
    string fileName = "";
   var   mockClient = new Mock<IHttpHandler>();

    this._iADLS_Operations = new ADLS_Operations(mockClient.Object);

    mockClient.Setup(repo => repo.PostAsync(It.IsAny<string>(), It.IsAny<HttpContent>(), It.IsAny<string>()))
        .Returns(() => Task.FromResult(new HttpResponseMessage(HttpStatusCode.BadRequest)));

    mockClient.Setup(repo => repo.SendAsync(It.IsAny<HttpRequestMessage>(), It.IsAny<string>()))
        .Returns(() => Task.FromResult(new HttpResponseMessage(HttpStatusCode.BadRequest)));  // here I want to return Exception instead of BadRequest. How to do that.

    Exception ex = Assert.Throws<Exception>(() => this._iADLS_Operations.CreateCSVFile(dtData, fileName).Result);
    Assert.Contains("Exception occurred while executing method:", ex.Message);
}

在下面的代码中,我想返回 Exception 而不是 BadRequest

mockClient.Setup(repo => repo.SendAsync(It.IsAny<HttpRequestMessage>(), It.IsAny<string>()))
    .Returns(() => Task.FromResult(new HttpResponseMessage(HttpStatusCode.BadRequest)));

如何实现。

最佳答案

考虑到被测代码的异步性,如果测试代码也是异步的会更好。 Moq 具有异步能力

[Fact]
public async Task CreateCSVFile_Failure() {
    //Arrange
    var dtData = new DataTable();
    string fileName = "";
    var mockClient = new Mock<IHttpHandler>();

    this._iADLS_Operations = new ADLS_Operations(mockClient.Object);

    mockClient
        .Setup(repo => repo.PostAsync(It.IsAny<string>(), It.IsAny<HttpContent>(), It.IsAny<string>()))
        .ReturnsAsync(new HttpResponseMessage(HttpStatusCode.BadRequest));

    mockClient
        .Setup(repo => repo.SendAsync(It.IsAny<HttpRequestMessage>(), It.IsAny<string>()))
        .ThrowsAsync(new Exception("Some message here"));

    //Act 
    Func<Task> act = () => this._iADLS_Operations.CreateCSVFile(dtData, fileName);

    //Assert
    Exception ex = await Assert.ThrowsAsync<Exception>(act);
    Assert.Contains("Exception occurred while executing method:", ex.Message);
}

注意在设置中使用 Moq 的 ReturnsAsyncThrowsAsync,以及 xUnit 的 Assert.ThrowsAsync

这现在可以让您避免像 .Result 这样可能导致死锁的阻塞调用。

关于c# - 如何使用 Moq 为异步函数抛出异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57094898/

相关文章:

c# - 尝试创建一个包含 2 个插入的存储过程

c - 如何使用 GLib 框架运行单元测试?

python - 将 Python 的 stdout 传递给写入的 C 函数

macos - 点网 : command not found in Mac

c# - 如何将 Controller 操作绑定(bind)到引用的 dll 中的模型

c# - 对包含两个项目的列表进行排序并在 C# 中转换为大写的错误结果

c# - 400 错误请求,Azure 服务管理 api 配置更改

c# - .NET 数据模型显示为 XML 而不是图表

javascript - 揭示模块中的依赖注入(inject)

javascript - Kendo UI - 将参数传递给 read().data() 中的 JS 函数