检查单元测试中是否抛出参数

时间:2012-01-05 15:16:17

标签: c# unit-testing try-catch

我正在为一个应用程序进行单元测试,该应用程序有一个构造函数,它将三个值作为参数。数字应为0或更高,现在我正在编写一个单元测试,用于抛出异常的构造函数,如果不是这样的话。

我无法弄清楚我是如何在“断言”之后编写的,以确定这一点,以便在非法数字传递给构造函数时测试通过。提前谢谢。

编辑:我正在使用MSTest框架

   public void uniqueSidesTest2()
    {
        try {
            Triangle_Accessor target = new Triangle_Accessor(0, 10, 10);
        }
        catch (){
            Assert // true (pass the test)
            return;
        }

        Assert. // false (test fails)
    }

//来自代码......

    public Triangle(double a, double b, double c) {
        if ((a <= 0) || (b <= 0) || (c <= 0)){
            throw new ArgumentException("The numbers must higher than 0.");
        }
        sides = new double[] { a, b, c };
    }

6 个答案:

答案 0 :(得分:8)

首先,您应该抛出ArgumentOutOfRangeException而不仅仅是ArgumentException

其次,你的单元测试应该会抛出异常,就像这样:

[ExpectedException(typeof(ArgumentOutOfRangeException))]
public static void MyUnitTestForArgumentA()
{
    ...
}

因此,您需要创建单独的单元测试 - 每个参数一个 - 测试当参数超出范围时方法是否抛出正确的异常。

答案 1 :(得分:3)

无需使用try catch块。使用NUnit或MSTest框架,您可以在测试方法声明中使用属性来指定您期望的异常。

MSTest的

 [TestMethod]
 [ExpectedException(typeof(ArgumentException))]
 public void uniqueSidesTest2()

答案 2 :(得分:2)

它可能不是最佳解决方案,但如果我正在测试以确保抛出异常,我将执行以下操作:

public void uniqueSidesTest2()
{
    try {
        Triangle_Accessor target = new Triangle_Accessor(0, 10, 10);
        Assert.Fail("An exception was not thrown for an invalid argument.");
    }
    catch (ArgumentException ex){
        //Do nothing, test passes if Assert.Fail() was not called
    }
}

由于构造函数调用应该抛出错误,如果它到达第二行(Assert.Fail()行),那么你知道它没有正确抛出异常。

答案 3 :(得分:2)

如果您没有nunit(或其他内置此支持的框架,您可以使用以下类型的帮助方法

 public static void ThrowsExceptionOfType<T>(Action action) where T: Exception
    {
        try
        {
            action();
        }
        catch (T)
        {
            return;
        }
        catch (Exception exp)
        {
            throw new Exception(string.Format("Assert failed. Expecting exception of type {0} but got {1}.", typeof(T).Name, exp.GetType().Name));
        }

        throw new Exception(string.Format("Assert failed. Expecting exception of type {0} but no exception was thrown.", typeof(T).Name));
    }

您的测试看起来像这样

AssertHelper.ThrowsExceptionOfType<ArgumentException>( 
    () => 
    {
        new Triangle_Accessor(0, 10, 10);
    });

答案 4 :(得分:0)

catch中不需要断言(但您可能希望捕获更具体的异常,例如ArgumentException)。

总是失败,有Assert.Fail

答案 5 :(得分:0)

你没有提到你用于单元测试的框架,但我认为你正在寻找的东西就像这里显示的那样:

http://www.nunit.org/index.php?p=exception&r=2.4