用于异常处理的NUnit C#语法

时间:2013-01-11 12:35:25

标签: c# exception nunit

我需要为一些枚举值集合编写测试。 当使用其中的一部分时,我期待一个例外,我的测试需要处理它。

我可以使用[ExpectedException]和我的枚举值的参数编写测试方法。 我可以编写使用foreach的方法来枚举预期会引发异常的枚举值。但在这种情况下,我认为会引发第一个异常,并且不会检查其余的枚举值。

如何正确枚举枚举值并使用单个或2个方法检查异常?

我只是不想为每个需要检查的枚举值设置一个新方法。

3 个答案:

答案 0 :(得分:4)

您可以将NUnits参数化测试与TestCase属性一起使用。

这将允许您编写两个测试:一个用于应该抛出异常的枚举值,另一个用于不应该抛出异常的枚举值。

[Test]
[TestCase(MyEnum.ExceptionValue1)]
[TestCase(MyEnum.ExceptionValue2)]
[TestCase(MyEnum.ExceptionValue3)]
public void MethodShouldThrowForInvalidValues(MyEnum value)
{
    var sut = new MyClass();

    Assert.Throws<MyException>(() => sut.MyMethod(value));
}

[Test]
[TestCase(MyEnum.ValidValue1)]
[TestCase(MyEnum.ValidValue2)]
[TestCase(MyEnum.ValidValue3)]
public void MethodShouldNotThrowForValidValues(MyEnum value)
{
    var sut = new MyClass();

    sut.MyMethod(value);

    Assert.True(true);
}

另一种方法是使用一个类型或属性来返回该方法应该抛出异常的所有枚举值:

[Test]
[TestCaseSource("InvalidEnumValues")]
public void MethodShouldThrowForInvalidValues(MyEnum value)
{
    var sut = new MyClass();

    Assert.Throws<MyException>(() => sut.MyMethod(value));
}


public IEnumerable<MyEnum> InvalidEnumValues
{
    get
    {
        // here you can put a foreach if you like
    }
}

答案 1 :(得分:0)

您的测试代码可能如下所示。考虑将TestMethod拆分为两个方法,这样就不需要传递bool标志

[TestFixture]
class Test
{

    [TestCase(MyEnum.Foo, false)]
    [TestCase(MyEnum.Bar, true)]
    public void TestMethod(MyEnum myEnum, bool shouldExceptionBeThrown)
    {
        if (shouldExceptionBeThrown)
            Assert.Throws<Exception>(() => MethodUnderTest(myEnum));
        else
            MethodUnderTest(myEnum);
    }

    public void MethodUnderTest(MyEnum myEnum)
    {
        if(myEnum == MyEnum.Bar)
            throw new Exception();
    }
}

internal enum MyEnum
{
    Foo,
    Bar
}

答案 2 :(得分:0)

以下是TestCaseSource如何为大数据驱动测试提供帮助的示例:

这是一种定义测试数据源的方法 -

private class InputData
{
    private Dictionary<string, string> _keywords;
    public InputData()
    {
        _keywords = new Dictionary<string, string>
                       {
                           {"abc", "test case 1"},
                           {"xyz", "test case 2"},
                       };
    }
}

它的用法:

[TestCaseSource(typeof(InputData), "_keywords")]
public void MethodShouldNotThrowForValidValues(KeyValuePair<string, string> value)
{
    var sut = new MyClass();

    var val = sut.MyMethod(value);

    Assert.True(val);
}