在NUnit 3中使用[TestCase]属性测试异常吗? [英] Testing for exceptions with [TestCase] attribute in NUnit 3?

查看:274
本文介绍了在NUnit 3中使用[TestCase]属性测试异常吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何使用NUnit3在TestCase中测试异常?

假设我有一个方法 Divide (a,b)定义如下:

Let's say I have a method Divide(a,b) defined as follows:

public double Divide(double a, double b)
{
    if(Math.Abs(b) < double.Epsilon) throw new ArgumentException("Divider cannot be 0");
    return a/b;
}

我想使用NUnit 3.0测试用例测试此方法,所以也许我有:

I want to test this method using NUnit 3.0 test cases, so maybe I have:

[TestCase(-10, 2, -5)]
[TestCase(-1, 2, -0.5)]
public void TestDivide(double a, double b, double result)
{
    Assert.That(_uut.Divide(a, b), Is.EqualTo(result));
}

是否有一种方法可以指定导致Divide()的测试用例抛出ArgumentException并以某种方式将其作为预期结果,例如

Is there a way to specify a Test Case that will cause Divide() to throw an ArgumentException and somehow have this as the expected result, e.g. something along the lines of:

[TestCase(-10, 2, -5)]
[TestCase(-1, 2, -0.5)]
[TestCase(-1, 0, ExpectedResult = TypeOf(ArgumentException)]
public void TestDivide(double a, double b, double result)
{
    Assert.That(_uut.Divide(a, b), Is.EqualTo(result));
}

(当然,我可以定义一个单独的测试方法,并在其中使用 Assert.Throws(),所以这完全出于好奇)

(Of course I could define a separate test method and use Assert.Throws() in this, so this is purely out of curiosity)

推荐答案

ExpectedException 对于NUnit 2.X是正确的方法,但它已从NUnit 3中删除。

ExpectedException would have been the correct method for NUnit 2.X, but it was removed from NUnit 3.

NUnit Google小组和同等的Dev小组-但似乎已决定,这通常是测试预期结果的更好的设计模式,并采用单独方法进行例外处理。(链接

There's a various snippets of discussion in the NUnit Google Group and the equivalent Dev group - but it looks like the decision was made that it's generally a better design pattern to test expected outcomes, and exceptions in separate methods. (link)

在NUnit 3中执行此操作的唯一方法是将其分解为两个单独的测试。 (在NUnit核心团队回答的类似问题中,此处。)

The only way to do this in NUnit 3, would be to break it down in to two separate tests. (Confirmed in a similar question answered by the NUnit core team, here.)

[TestCase(-10, 2, -5)]
[TestCase(-1, 2, -0.5)]
public void TestDivide(double a, double b, double result)
{
    Assert.That(_uut.Divide(a, b), Is.EqualTo(result));
}

[TestCase(-1, 0)]
public void TestDivideThrows(double a, double b)
{
    Assert.That(() => _uut.Divide(a, b), Throws.TypeOf<ArgumentException>());
}

这篇关于在NUnit 3中使用[TestCase]属性测试异常吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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