0

I have this:

  Expect.Once.On( someObj ).Method( "SomeMethod" )
    .With(1) // correct value is 2, I want this to fail
    .Will( Throw.Exception( new Exception() ) );

An exception is thrown by nmock when it detects that I put 1 instead of 2. However, the test is failing (red) instead of passing. How to make this test pass, even though I'm expecting an exception?

O.O
  • 11,077
  • 18
  • 94
  • 182
  • What unit test framework are you using? – 48klocs Jun 25 '12 at 17:38
  • MSTest. However, it's nmock that I care about here, not how other testing frameworks do this. – O.O Jun 25 '12 at 17:40
  • @O.O - NMock is a mocking framework, not a unit testing framework. You will still need to assert the exception thrown from the mock is expected in your tests. – Lee Jun 25 '12 at 17:48

2 Answers2

5

If you're using NUnit then you can do:

Assert.Throws<Exception>(() => { someObj.SomeMethod(1); });

You can also decorate the test with an ExpectedException attribute, although that will cause the test to pass if any Exception is thrown, rather than just the statement you want to test.

EDIT: If you're using MSTest, as far as I know, you can only use attributes to expect exceptions i.e.

[ExpectedException(typeof(Exception)]
public void TestMethod() { ... }

You should consider throwing a more specific exception type from your mock and expecting that type instead of a plain Exception.

You could also define your own method to replicate the NUnit functionality:

public static class ExceptionAssert
{
    public static void Throws<T>(Action act) where T : Exception
    {
        try
        {
            act();
        }
        catch (T ex)
        {
            return;
        }
        catch (Exception ex)
        {
            Assert.Fail(string.Format("Unexpected exception of type {0} thrown", ex.GetType().Name));
        }

        Assert.Fail(string.Format("Expected exception of type {0}", typeof(T).Name));
    }
}
Lee
  • 142,018
  • 20
  • 234
  • 287
2
[ExpectedException (typeof(Exception))]

Edit: thanks, don't have the studio right now and was not 100% sure about the syntax.

AD.Net
  • 13,352
  • 2
  • 28
  • 47