C#:如何检查“未发生异常"?在我的MSTest单元测试中? [英] C#: How do I check "no exception occurred" in my MSTest unit test?

查看:193
本文介绍了C#:如何检查“未发生异常"?在我的MSTest单元测试中?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在为此返回"void"的方法编写单元测试.我希望有一种情况,即在没有引发异常的情况下测试通过.我该如何用C#编写代码?

I'm writing a unit test for this one method which returns "void". I would like to have one case that the test passes when there is no exception thrown. How do I write that in C#?

Assert.IsTrue(????)

(我的猜测是这是我应该检查的方式,但是"???"中出现的内容)

(My guess is this is how I should check, but what goes into "???")

我希望我的问题很清楚.

I hope my question is clear enough.

推荐答案

如果引发异常,您的单元测试仍然会失败-您不需要放入特殊的断言.

Your unit test will fail anyway if an exception is thrown - you don't need to put in a special assert.

这是您将看到根本没有断言的单元测试的少数情况之一-如果引发异常,则测试将隐式失败.

This is one of the few scenarios where you will see unit tests with no assertions at all - the test will implicitly fail if an exception is raised.

但是,如果您确实想为此写一个断言-也许能够捕获异常并报告没有异常但得到了这个...",则可以执行以下操作:

However, if you really did want to write an assertion for this - perhaps to be able to catch the exception and report "expected no exception but got this...", you can do this:

[Test]
public void TestNoExceptionIsThrownByMethodUnderTest()
{
    var myObject = new MyObject();

    try
    {
        myObject.MethodUnderTest();
    }
    catch (Exception ex)
    {
        Assert.Fail("Expected no exception, but got: " + ex.Message);
    }
}

(以上是NUnit的示例,但对于MSTest同样适用)

(the above is an example for NUnit, but the same holds true for MSTest)

这篇关于C#:如何检查“未发生异常"?在我的MSTest单元测试中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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