60

Is there a way to test the exception messages with shouldly?

An example:

public class MyException: Exception{
}

The method to be tested:

public class ClassUnderTest
{
    public void DoSomething() 
    {
        throw new MyException("Message");
    }
}

I would usually test this in this way:

[TestMethod]
public void Test()
{
    try
    {
        new ClassUnderTest().DoSomething();
        Assert.Fail("Exception not thrown");
    } catch(MyException me)
    {
        Assert.AreEqual("Message", me.Message);
    }catch(Exception e)
       Assert.Fail("Wrong exception thrown");
    }
}

With shouldly I can now test if a exception is thrown:

[TestMethod]
public void TestWithShouldly()
{
    Should.ThrowException<MyException>(() => new ClassUnderTest().DoSomething());
}

But how can I test the message of the exception?

Steffen
  • 2,381
  • 4
  • 20
  • 33

1 Answers1

97

The Should.Throw() method returns the exception, so you can continue to test if for other things.

For example:

Should.Throw<MyException>(() => new ClassUnderTest().DoSomething())
    .Message.ShouldBe("My Custom Message");

Or, if you want to do more than just test the message:

MyException ex = Should.Throw<MyException>(() => new ClassUnderTest().DoSomething());

You can then do what you like with ex.

Note: Shouldly V2 uses Should.ThrowException<>()

Matthew Lock
  • 13,144
  • 12
  • 92
  • 130
Colin Mackay
  • 18,736
  • 7
  • 61
  • 88
  • Damn, so simple. Should have figured it out myself. Thank you – Steffen Nov 11 '16 at 09:53
  • 17
    Apparently, in latest versions it should be `Throw` – Noctis Oct 03 '17 at 16:17
  • What do you do if your Action takes a ref and can't be used in a lambda? > Cannot use ref local inside an anonymous method, lambda expression, or query expression – Steve Jun 21 '23 at 19:12