Search code examples
c#unit-testingvs-unit-testing-frameworkexpected-exception

Ensure that the method under test has thrown the expected exception, NOT any other part of the test case set up


I am using Visual Studio Unit Test Cases. I have written the Unit test case where Argument Exception is expected from the method under test MethodUnderTest. Suppose if any other part of the test case (Setup part) throws the expected exception ArgumentException, Then I want to enforce that my test case should fail. It should pass only in case Setup is correct and instance.MethodUnderTest(); line of code throws ArgumentException.

I can achieve using try catch, but I want to know is there any better approach to achieve this.

[ExpectedException(typeof(ArgumentException))]
public void TestCaseMethod()
{        
    // Set up
    Mock<ITestClass> testM = new Mock<ITestClass>();
    AnimalClass instance = new AnimalClass(testM.Object);

    // call the method under test
    instance.MethodUnderTest();
}

Solution

  • I don't know of any built in way, but you could wrap up the method in an assert exception

    private void AssertException<T>(Action method)
        where T : Exception
    {
        try
        {
            method();
            Assert.Fail();
        }
        catch (T e)
        {
            Assert.IsTrue(true);
        }
    }
    

    Then call with

    [TestMethod]
    public void TestCaseMethod()
    {        
        // Set up
        Mock<ITestClass> testM = new Mock<ITestClass>();
        AnimalClass instance = new AnimalClass(testM.Object);
    
        // call the method under test
        AssertException<ArgumentException>(instance.MethodUnderTest)
    }
    

    Or, if your method takes in parameters or returns values

    AssertException<MyException>(() => instance.ParameterisedFunction(a, b));