应该测试exception消息
有没有办法用shouldly测试exception消息?
一个例子:
public class MyException: Exception{ }
要测试的方法:
public class ClassUnderTest { public void DoSomething() { throw new MyException("Message"); } }
我通常会以这种方式测试它:
[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"); } }
我应该现在可以测试是否抛出exception:
[TestMethod] public void TestWithShouldly() { Should.ThrowException(() => new ClassUnderTest().DoSomething()); }
但是我如何测试exception的消息呢?
Should.ThrowException()
方法返回exception,因此您可以继续测试是否有其他事情。
例如:
Should.ThrowException(() => new ClassUnderTest().DoSomething()) .Message.ShouldBe("My Custom Message");
或者,如果您想要做的不仅仅是测试消息:
MyException ex = Should.ThrowException(() => new ClassUnderTest().DoSomething());
然后你可以用ex
做你喜欢的事。