O.O
O.O

Reputation: 11307

How to expect an exception and still pass the test?

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?

Upvotes: 0

Views: 2620

Answers (2)

Lee
Lee

Reputation: 144136

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));
    }
}

Upvotes: 5

AD.Net
AD.Net

Reputation: 13399

[ExpectedException (typeof(Exception))]

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

Upvotes: 2

Related Questions