views:

65

answers:

1

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?

A: 

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 :)

Grzenio
Thanks I tested your code and I think I know now why it never was equal. The message in the exception is larger due to a more detailed error message:"Actual differs from expected\r\nInvocation was not performed on the mock: writeMessage => writeMessage.Info(\"This should fail\")"But thanks for the hint! And even though this test runs over production code.. Yes I'm playing around with framework ;-)
Mark