Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Handle expected exception in unit test in MSTest

I am testing DoingSomething() method with the following test method-

[TestMethod()]
[ExpectedException(typeof(ArgumentException),"Invalid currency.")]
public void ConvertCurrencyTest_ExhangeRate()
{
    try
    {
        DoingSomething();
    }
    catch (ArgumentException Ex)
    {
    }
    catch (Exception Ex)
    {
        Assert.Fail();
    }
}

Test result says that DoingSomething() did not throw an exception. But it thrown exception indeed.

What did I miss here?

like image 755
s.k.paul Avatar asked Dec 18 '22 06:12

s.k.paul


1 Answers

You are consuming the exception in your try/catch so it is not bubbling up to be caught by the test.

Remove the try/catch and let the test harness handle the exception. Any other exception would naturally cause the test to fail anyway.

[TestMethod()]
[ExpectedException(typeof(ArgumentException),"Invalid currency.")]
public void ConvertCurrencyTest_ExhangeRate() {       
    DoingSomething();        
}
like image 135
Nkosi Avatar answered Dec 24 '22 00:12

Nkosi