Test passes while exception is thrown

Viewed 110

I've the following test in Nunit with 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>());
    }
    
}

and the following method that is tested:

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

Is expect the test to fail, but when I run it in Visual Studio it passes. I can't get my head around it, tests should fail when an unexpected exception is thrown, right? So why does it pass?

1 Answers

SendAsync ran successfully, and returned a Task which contained an exception (its IsFaulted property returns true, and its Exception property contains the NotImplementedException).

However, you're not checking the Task which is returned from SendAsync, so you never realise that it contains an exception.

The easiest way to check the Task for exceptions is using await, and make your test method async Task. This also handles the case where the Task doesn't complete straight away.

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