简体   繁体   English

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

[英]Checking if argument is thrown in unit-tests

I'm working on unit-tests for an application which has a constructor that takes three values as arguments. 我正在为一个应用程序进行单元测试,该应用程序有一个构造函数,它将三个值作为参数。 The numbers shall be 0 or higher, and now I'm writing on an unit-test for the constructor that throws an exception if this is not the case. 数字应为0或更高,现在我正在编写一个单元测试,用于抛出异常的构造函数,如果不是这样的话。

What I can't figure out is how I what to write after "Assert" to determine this so that the test passes if illegal numbers are passed to the constructor. 我无法弄清楚的是我如何在“断言”之后写什么来确定这一点,以便在非法数字传递给构造函数时测试通过。 Thanks in advance. 提前致谢。

EDIT: I'm using MSTest framework 编辑:我正在使用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)
    }

// From the code... //从代码中......

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

First of all, you should throw an ArgumentOutOfRangeException rather than just an ArgumentException . 首先,您应该抛出ArgumentOutOfRangeException而不仅仅是ArgumentException

Second, your unit test should expect an Exception to be thrown, like so: 其次,你的单元测试应该期望抛出异常,如下所示:

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

So, you need to create separate unit tests -- one for each argument -- that test whether the method throws a correct exception when the argument is out of range. 因此,您需要创建单独的单元测试 - 每个参数一个 - 测试当参数超出范围时方法是否抛出正确的异常。

No need to use a try catch block. 无需使用try catch块。 Using NUnit or the MSTest framework you can use an attribute on your test method declaration to specify that you expect an exception. 使用NUnit或MSTest框架,您可以在测试方法声明中使用属性来指定您期望的异常。

MSTest MSTest的

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

It may not be the best solution, but if I'm testing to make sure an Exception is thrown, I will do something like the following: 它可能不是最好的解决方案,但如果我正在测试以确保抛出异常,我将执行以下操作:

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

Since your constructor call should throw an error, if it ever gets to the second line (The Assert.Fail() line) then you know it didn't properly throw the exception. 因为构造函数调用应该抛出一个错误,如果它到达第二行(Assert.Fail()行),那么你知道它没有正确抛出异常。

If you don't have nunit (or other framework that has this support built in you can use the following type of helper method 如果您没有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));
    }

Your test would look like this 你的测试看起来像这样

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

You will not need an Assert in the catch (but you might want to catch a more specific exception, like ArgumentException ). 你不需要在catch使用Assert(但是你可能想要捕获一个更具体的异常,比如ArgumentException )。

To always fail, there is an Assert.Fail . 总是失败,有一个Assert.Fail

You don't mention what framework you are using for unit testing, but I think what you're looking for is something like what is shown here: 你没有提到你用于单元测试的框架,但我认为你所寻找的是类似于这里显示的内容:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM