NUnit - ExpectedMessage has a bug

I am new to TDD and I'm going with NUnit and Moq. I have a method where I expect an exception, so I wanted to play a little with the functions of the framework.

My test code is 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 get an error message indicating that the error message is different from the expected message. What am I doing wrong?

+4
source share
2 answers

Unfortunately, the Resharper test under test has an error / limitation - it does not handle ExpectedException attributes. You have 2 options:

  • Use a different test runner (e.g. nunit-gui.exe, ships with NUnit), but this approach forces you to debug your tests

  • Print and check the exception manually using the following pattern:

    [Test] public void Write_MessageLogWithCategoryInfoFail () {try {string message = "Informational 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); } 

    }

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

On the side of the note, I hope the above code is only for playing with the framework - usually you will never catch MockExceptions :)

+3
source

You can use the optional parameter MatchType = MessageMatch.Regex .

+2
source

Source: https://habr.com/ru/post/1312304/


All Articles