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

时间:2019-07-18 12:51:29

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

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

我正在使用Test类中的以下代码来测试另一类方法的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)));

如何实现这一目标。

2 个答案:

答案 0 :(得分:2)

考虑到被测代码的异步特性,如果测试代码也是异步的,那就更好了。 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>()))
        .ThrowsAsyc(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之类的阻塞调用,这可能导致死锁。

答案 1 :(得分:1)

就像@Johnny在评论中提到的那样,您可以将代码中的Returns替换为Throws,例如:

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

此外,您还可以引发如下异常:

mockClient.Setup(repo => repo.SendAsync(It.IsAny<HttpRequestMessage>(), It.IsAny<string>())).Throws<InvalidOperationException>();

您可以找到有关引发异常和起订量here的更多信息。