Search code examples
c#nunitresharperexpected-exception

NUnit - ExpectedMessage differs error


I am quite new to TDD and am going with NUnit and Moq. I have got a method where I expect an exception, so I wanted to play a little with the frameworks features.

My test code looks as follows:

    [Test]
    [ExpectedException(ExpectedException = typeof(MockException), ExpectedMessage = "Actual differs from expected")]
    public void Write_MessageLogWithCategoryInfoFail()
    {
        string message = "Info Test Message";

        Write_MessageLogWithCategory(message, "Info");

        _LogTest.Verify(writeMessage =>
            writeMessage.Info("This should fail"),
            "Actual differs from expected"
        );
    }

But I always receive the errormessage that the error message that the actual exception message differs from the expected message. What am I doing wrong?


Solution

  • Unfortunately Resharper test runner has a bug/limitation - it doesn't handle the ExpectedException attributes. You have 2 options:

    1. Use some other test runner (e.g. nunit-gui.exe, shipped with NUnit) - but this approach makes it a pain to debug your tests

    2. Catch and validate the exception manually, using the following pattern:

      [Test] public void Write_MessageLogWithCategoryInfoFail() { try { string message = "Info Test Message";

        Write_MessageLogWithCategory(message, "Info");
      
        _LogTest.Verify(writeMessage =>
            writeMessage.Info("This should fail"),
            "Actual differs from expected"
        );
        Assert.Fail("Expected exception");
      }
      catch(MockException e)
      {
        Assert.AreEqual("Actual differs from expected", e.Message);
      }
      

      }

    Its a real shame, because the descriptive way of saying that you expect an exception is much nicer!

    On a side note I hope that the code above is only for playing with the framework - usually you would never catch MockExceptions :)