Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using try/catch blocks in unit tests

Using VS's testing framework, I'm currently writing my tests like this:

[TestMethod]
public void TestSomething() 
{
    try
    {
        var someTestValue = _someTestClass.SomeTestMethod();            

        Assert.IsNotNull(someTestValue);
    }
    catch (Exception e) 
    {
        Assert.Fail(e.Message);
    }
}

My logic is that if an exception is thrown in SomeTestMethod(), I'll immediately terminate the test displaying the exception message through Assert.Fail(e.Message).

The "normal way" of doing things would be:

[TestMethod]
public void TestSomething() 
{
    var someTestValue = _someTestClass.SomeTestMethod();            

    Assert.IsNotNull(someTestValue);
}

Is my approach correct, or is the "normal way" correct? Am I writing redundant code ?

like image 609
drl Avatar asked Dec 25 '22 11:12

drl


2 Answers

I'd say this is redundant, yes. If the exception is an unexpected result then the test fails. Whether it fails by throwing an exception or by failing an Assert is treated the same way by the testing framework. Basically, a failed test is a failed test.

like image 186
David Avatar answered Dec 28 '22 10:12

David


The testing framework will already fail the test if the test method throws an exception. You're adding extra work for no added value.

like image 30
Servy Avatar answered Dec 28 '22 10:12

Servy