Search code examples
c#unit-testingmstestassertvs-unit-testing-framework

More flexible Assert.ThrowsException?


MSTest now allows you to test that a certain piece of code throws a certain exception type, through:

Assert.ThrowsException<MyException>(() => foo.Bar());

However, I need a more flexible exception test; I need to not only test the type of the exception, but check that its message starts with a certain string (rather than matching the exact exception string). Is there a way I can do this with MSTest? If not, what's the best way for me to do it? Is there another testing framework that handles this better?

Ideally, the Assert would take in a second func that passed in the Exception thrown, and this func could test the Exception however it wanted and return true or false to indicate that the assert had succeeded or failed.


Solution

  • var ex = Assert.ThrowsException<MyException>(() => foo.Bar());
    Assert.IsTrue(ex.Message.StartsWith("prefix"));