Nunit async test exception assertion

后端 未结 6 1697
感情败类
感情败类 2020-12-29 18:37

[Edit (May 2020)] - This issue has been reportedly addressed in newer releases of NUnit. Please see Nunit.ThrowsAsync. (Ref this answer, thanks @James-Ross)

6条回答
  •  太阳男子
    2020-12-29 19:04

    I'm not sure when it was added, but the current version of Nunit (3.4.1 at time of writing) includes a ThrowsAsync method

    see https://github.com/nunit/docs/wiki/Assert.ThrowsAsync

    Example:

    [Test]
    public void ShouldThrow404WhenNotFound()
    {
        var mockUserRepository = new Mock();
        mockUserRepository.Setup(x => x.GetByUserName(It.IsAny())).Returns(default(User));
        var userController = new UserController(mockUserRepository.Object) { Request = new HttpRequestMessage() };
    
        var exception = Assert.ThrowsAsync(() => userController.Get("foo"));
    
        Assert.That(exception.Response.StatusCode, Is.EqualTo(HttpStatusCode.NotFound));
    }
    

提交回复
热议问题