抛出异常时测试通过

Test passes while exception is thrown

我在带有最小起订量的 Nunit 中进行了以下测试:

[TestFixture]
public class MessageServiceTests
{
    private Mock<IFtpClient> _ftpService;
    private IMessageService _messageService;

    [SetUp]
    public void Setup()
    {
        _ftpService = new Mock<IFtpClient>();

        _messageService = new MessageService(_ftpService.Object);
    }

    [Test]
    public void SendAsync_WithSettings_ConnectsWithCredentials()
    {
        //act
        _messageService.SendAsync(It.IsAny<Stream>(), It.IsAny<String>(), It.IsAny<Settings>());
    }
    
}

和下面测试的方法:

 public async Task SendAsync(Stream stream, string fileName, Settings settings)
    {
        throw new NotImplementedException();            
    }

预计测试会失败,但是当我 运行 它在 Visual Studio 时它通过了。我无法理解它,抛出意外异常时测试应该失败,对吗?那为什么会通过呢?

SendAsync 运行 成功,并返回一个包含异常的 Task (它的 IsFaulted 属性 returns true,其 Exception 属性 包含 NotImplementedException).

但是,您没有检查从 SendAsync 返回的 Task,因此您永远不会意识到它包含异常。

检查 Task 异常的最简单方法是使用 await,并使您的测试方法 async Task。这也处理了 Task 没有立即完成的情况。

[Test]
public async Task SendAsync_WithSettings_ConnectsWithCredentials()
{
    //act
    await _messageService.SendAsync(It.IsAny<Stream>(), It.IsAny<String>(), It.IsAny<Settings>());
}