Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

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

   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 };
    }
like image 247
holyredbeard Avatar asked Dec 03 '22 00:12

holyredbeard


2 Answers

First of all, you should throw an ArgumentOutOfRangeException rather than just an 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.

like image 62
Roy Dictus Avatar answered Dec 20 '22 12:12

Roy Dictus


No need to use a try catch block. Using NUnit or the MSTest framework you can use an attribute on your test method declaration to specify that you expect an exception.

MSTest

 [TestMethod]
 [ExpectedException(typeof(ArgumentException))]
 public void uniqueSidesTest2()
like image 41
Myles McDonnell Avatar answered Dec 20 '22 12:12

Myles McDonnell