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?
UPDATE: From Shouldly V3 this is now Should.Throw<>()
The Should.ThrowException()
method returns the exception, so you can continue to test if for other things.
For example:
Should.ThrowException<MyException>(() => new ClassUnderTest().DoSomething())
.Message.ShouldBe("My Custom Message");
Or, if you want to do more than just test the message:
MyException ex = Should.ThrowException<MyException>(() => new ClassUnderTest().DoSomething());
You can then do what you like with ex
.
来源:https://stackoverflow.com/questions/40543708/testing-exception-messages-with-shouldly