C# – How to simulate events that cause exceptions to test try/catch blocks

cexceptionstesting

I understand how exceptions work and how to catch and handle them in C# but how can I simulate events that may cause an exception to ensure that it is caught correctly? For example, is it possible to run an application in a kind of test bed where it's possible to simulate network problems, database problems, etc? Exceptions by their nature seem hard to reproduce thus making it hard to ensure your code can cope with them.

Although I mainly develop using C#/.NET/Visual Studio, answers or resources relating to other languages could be useful.

Best Answer

1) If you followed the dependency injection model, you could substitute real implementations of certain parts with the mocks which would throw exceptions as you need them. That would however require of you to initially design your application in a specific way or completely reengineer it.

Like:

public class SqlUsersRepository : IUsersRepository
{
    public void RegisterNewUser (User newUser)
    {
        throw new SqlException ("Connection timeout");
    }
}

Here however we would have the problem that the consumer code shouldn't concern itself with handling concrete implementation exceptions.

2) Another approach is to replace certain method calls with your custom wrappers.

Instead of:

FileStream fs = File.OpenRead (path);

you use:

FileStream fs = File.OpenRead_Test (path);

by providing a custom extension method (just a quick idea):

public static FileStream OpenRead_Test (this System.IO.File file, string path)
{
    throw new FileNotFoundException ();
}