C# 使用Shouldly测试异常消息

C# 使用Shouldly测试异常消息,c#,exception-handling,shouldly,C#,Exception Handling,Shouldly,有没有办法用shouldly测试异常消息 例如: public class MyException: Exception{ } 要测试的方法: public class ClassUnderTest { public void DoSomething() { throw new MyException("Message"); } } 我通常会这样测试: [TestMethod] public void Test() { try {

有没有办法用shouldly测试异常消息

例如:

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");
    }
}
使用shouldly,我现在可以测试是否引发异常:

[TestMethod]
public void TestWithShouldly()
{
    Should.ThrowException<MyException>(() => new ClassUnderTest().DoSomething());
}
[TestMethod]
公共void TestWithShouldly()
{
Should.throweexception(()=>newclassundertest().DoSomething());
}
但是如何测试异常的消息呢?

方法
应该.Throw()
返回异常,因此您可以继续测试是否有其他异常

例如:

Should.Throw<MyException>(() => new ClassUnderTest().DoSomething())
    .Message.ShouldBe("My Custom Message");
Should.Throw(()=>newclassundertest().DoSomething())
.Message.ShouldBe(“我的自定义邮件”);
或者,如果您想做的不仅仅是测试消息:

MyException ex = Should.Throw<MyException>(() => new ClassUnderTest().DoSomething());
MyException ex=Should.Throw(()=>newclassundertest().DoSomething());
然后,您可以使用
ex
执行您喜欢的操作


注意:应该使用
Should.throweexception()

该死,太简单了。我应该自己解决的。显然,在最新版本中,它应该是
Throw