测试异常消息 [英] Testing Exception Messages with Shouldly

查看:113
本文介绍了测试异常消息的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



一个例子:

  public class MyException:异常{
}

被测试:

  public class ClassUnderTest 
{
public void DoSomething()
{
抛出新的MyException(Message);
}
}

我通常会以这种方式测试: p>

  [TestMethod] 
public void Test()
{
try
{
new ClassUnderTest()。DoSomething();
Assert.Fail(Exception not throwwn);
} catch(MyException me)
{
Assert.AreEqual(Message,me.Message);
} catch(异常e)
Assert.Fail(抛出异常);
}
}

我现在可以测试是否抛出异常:

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

但是如何测试异常的消息?

解决方案

Should.ThrowException()方法返回异常,所以你可以继续测试如果是其他的东西。



例如:

  Should.ThrowException< ; MyException>(()=> new ClassUnderTest()。DoSomething())
.Message.ShouldBe(我的自定义消息);

或者,如果你想做的不仅仅是测试消息:

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

然后,您可以使用 ex


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?

解决方案

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.

这篇关于测试异常消息的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆