Search code examples
c#exceptiontestingfitnesse

throw new Exception in a test


While browsing the code of my application I faced this:

private string[] ReadFromFile(string path)
{
    string[] data = null;
    try
    {
        data = File.ReadAllLines(path);
    }
    catch (Exception)
    {
        throw new Exception("The file is not correct");
    }

    return data;
}

Ok so I know this code is not good and I was about to refactor this. However, this code is used in the definition of some tests for FitNesse. This code is never used in production. The parameter given in this method is supposed to be always correct. So I feel like removing the whole try/catch block and let it crash if it should. FitNesse would give us the whole details about the exception thrown, but since it's a test fixture I'm wondering if it may be ok.

File.ReadAllLines can throw a dozen of different exceptions.

So my question: Is it acceptable to have such kind of code, outside production, even if used to test production code, and in a environment under control? Or is it bad under any circumstances?


Solution

  • It is even worse to have such code in unit tests than having it in production code. In production code sometimes it might make a sense to hide some exception details (though they still should be delivered via InnerException for example) but in unit tests you should always see as much as possible because they are done for you (developer, not end user). So I think this entire try/catch block should be removed.

    Also if in some other case you would like to fail test then I would recommend using Assert.Fail("message") construction since it makes it more clear then tests should be treated as failed if it reached this point. Not sure whether it can be applied to FitNesse though.