English 中文(简体)
NUnit的TestCustomException不关心异常类型
原标题:NUnit s TestCustomException doesn t care about the exception type

如果我想测试一个方法是否抛出特定类型的异常,NUnit的ExpectedException属性并不关心实际类型;如果在方法调用之前抛出一个泛型Exception,则测试通过:

    [Test, ExpectedException(typeof(TestCustomException))]
    public void FirstOnEmptyEnumerable()
    {
        throw new Exception(); // with this, the test should fail, but it doesn t
        this.emptyEnumerable.First(new TestCustomException());
    }

如果我想检查测试是否抛出了确切的异常类型,我必须手动执行如下操作:

    [Test]
    public void FirstOnEmptyEnumerable()
    {
        try
        {
            throw new Exception();  // now the test fails correctly.
            this.emptyEnumerable.First(new TestCustomException());
        }
        catch (TestCustomException)
        {
            return;
        }

        Assert.Fail("Exception not thrown.");
    }

我是不是错过了什么?

最佳回答

我从来没有使用过ExpectedException,所以我没有任何经验可以分享。一个选项是断言它直接抛出到测试内部。类似于以下内容:

[Test]
public void FirstOnEmptyEnumerable()
{
    Assert.Throws<TestCustomException>(() => this.emptyEnumerable.First(new TestCustomException()));
}

当您测试异常时,我发现这种方法更具可读性,因为它正是您期望它发生的地方,而不是说“在这个函数的某个地方,我除了要抛出的异常”。

问题回答

我总是测试异常的字符串表示,例如:

[Test, ExpectedException("Your.Namespace.TestCustomException")]
public void FirstOnEmptyEnumerable()
{
    throw new Exception(); // with this, the test should fail, but it doesn t
    this.emptyEnumerable.First(new TestCustomException());
}

这对我来说似乎很好。

如果要使用ExpectedException(字符串)签名,最佳做法是使用typeof(Exception).Name和typeof(Exception).Namespace





相关问题
Anyone feel like passing it forward?

I m the only developer in my company, and am getting along well as an autodidact, but I know I m missing out on the education one gets from working with and having code reviewed by more senior devs. ...

NSArray s, Primitive types and Boxing Oh My!

I m pretty new to the Objective-C world and I have a long history with .net/C# so naturally I m inclined to use my C# wits. Now here s the question: I feel really inclined to create some type of ...

C# Marshal / Pinvoke CBitmap?

I cannot figure out how to marshal a C++ CBitmap to a C# Bitmap or Image class. My import looks like this: [DllImport(@"test.dll", CharSet = CharSet.Unicode)] public static extern IntPtr ...

How to Use Ghostscript DLL to convert PDF to PDF/A

How to user GhostScript DLL to convert PDF to PDF/A. I know I kind of have to call the exported function of gsdll32.dll whose name is gsapi_init_with_args, but how do i pass the right arguments? BTW, ...

Linqy no matchy

Maybe it s something I m doing wrong. I m just learning Linq because I m bored. And so far so good. I made a little program and it basically just outputs all matches (foreach) into a label control. ...

热门标签