0

I am pretty new to unit testing and NUnit, my case is that a test expecting a simple exception stopped working when I changed from the Ninject NSubstitute mocking kernel adapter to plain NSubstitute for mocking Returns purposes.

    private IRecordRepository RecordRepositorySeed()
    {
        var repository = Substitute.For<IRecordRepository>();

        record.GetSingleAsync(r => r.Id == "1").Returns(new Task<Record>(() => new Record(...))); // sample record

        return repository;
    }

    [Test]
    [ExpectedException(typeof(NullReferenceException))]
    public void UnexistantRecord()
    {
        var billingService = new BillingService(RecordRepositorySeed());
        billingService.GenerateBill("5", "test");
    }

The test dont pass as it outputs that the test is expecting the System.NullReferenceException.

I debugged the tested method and it is actually triggering it:

//After a query on record that returns null, this snippet goes on
if (record == null)
{
    //It's reaching this part
    throw new NullReferenceException("record not found");
}

I tried these solutions but none of them worked for me:

NUnit expected exceptions

NUnit unit test has ExpectedException but still failing on exception

The thing is this test was working before I changed the mock to the Substitute syntax and I'm unable to figure out what's wrong with this approach.

I'm not sure if it is relevant but the GenerateBill method is async void

Community
  • 1
  • 1
Miguel A. Arilla
  • 5,058
  • 1
  • 14
  • 27
  • So the test is failing because NUnit is expecting the exception but it is not being thrown? Does it pass if you remove the `record.GetSingleAsync(...).Returns(...)` line? – David Tchepak Sep 22 '15 at 00:19
  • @DavidTchepak Nope, not working that way either, the code it's actually "throwing" the exception, but the test can't recognize it – Miguel A. Arilla Sep 22 '15 at 06:28
  • 1
    If `GenerateBill` is `async void`, maybe the call hasn't completed when the test ends? I'm not sure how the change from the mocking adapter would affect this behaviour, but it might be something worth looking at. – David Tchepak Sep 23 '15 at 00:23
  • @DavidTchepak You were right, I made the test async with an await call to GenerateBills and works like a charm ;) – Miguel A. Arilla Sep 23 '15 at 10:27

0 Answers0