How can I simulate an exception being thrown in C# unit tests?
I want to be able to have 100% coverage of my code, but I can’t test the code with exceptions that may occur. For example I cannot simulate a power faluire that may occur.
For example:
public void MyMethod()
{
try
{
...
}
catch(OutOfMemoryException e)
{
...
}
catch(RandomErrorFromDatabaseLayer e)
{
...
}
}
I want to be able to simulate any kind of exception that is in this method and should be caught.
Are there any libraries that may help me in this matter?
Edit 1:
Any help in accomplishing what I asked with Moq?
You need to create a mock object that stands in for the real objects that can throw these exceptions. Then you can create tests that simply are something like this:
If you are using a dependency injection framework it makes replacing the real code with the mock code much easier.