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

cha*_*har 6 c# unit-testing moq xunit .net-core

我正在使用 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);
}
Run Code Online (Sandbox Code Playgroud)

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

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

如何实现这一目标。

Nko*_*osi 15

考虑到被测代码的异步性质,如果测试代码也是异步的会更好。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);
}
Run Code Online (Sandbox Code Playgroud)

注意在设置中使用 MoqReturnsAsyncThrowsAsyncxUnit 以及Assert.ThrowsAsync

这现在允许您避免进行.Result可能导致死锁的阻塞调用。


小智 5

正如@Johnny 在评论中提到的,您可以将Returns代码中的 替换为Throws

mockClient.Setup(repo => repo.SendAsync(It.IsAny<HttpRequestMessage>(), It.IsAny<string>()))
  .Throws(new Exception("exception message"));
Run Code Online (Sandbox Code Playgroud)

此外,您还可以抛出异常,例如:

mockClient.Setup(repo => repo.SendAsync(It.IsAny<HttpRequestMessage>(), It.IsAny<string>()))
  .Throws<InvalidOperationException>();
Run Code Online (Sandbox Code Playgroud)

您可以在此处找到有关引发异常和最小起订量的更多信息。