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

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

问题描述

我正在为一个返回void的方法编写单元测试。当没有异常抛出时,我想要一个测试通过的情况。如何在C#中写?

  Assert.IsTrue(????)

(我猜这是我应该检查的,但是进入???)



我希望我的问题足够清楚。

解决方案

如果抛出异常,您的单元测试将失败 - 您不需要特别声明。



这是少数几种情况之一,您将看到单元测试根本没有断言 - 测试将如果引发异常,则会隐含地失败。



但是,如果你真的想为此写一个断言 - 也许能够捕获异常并报告预期的例外,但得到这个...,你可以这样做:

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

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

(以上是NUnit的一个例子,同样适用于MSTest)


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);
    }
}

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

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

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