【问题标题】:Test passes while exception is thrown抛出异常时测试通过
【发布时间】:2020-11-09 12:00:47
【问题描述】:

我在 Nunit 中使用 Moq 进行了以下测试:

[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 中运行它时它会通过。我无法理解它,当抛出意外异常时测试应该失败,对吧?那为什么会通过呢?

【问题讨论】:

    标签: c# unit-testing nunit moq


    【解决方案1】:

    SendAsync 运行成功,返回了一个包含异常的Task(其IsFaulted 属性返回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>());
    }
    

    【讨论】:

      猜你喜欢
      • 2014-12-07
      • 1970-01-01
      • 2013-09-08
      • 2020-08-18
      • 2014-05-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多