public int ReturnFromDB(int input)
{
try
{
return repositorymethod(input);
}
catch(RepositoryException ex)
{
Throw new ParticularException("some message",ex);
}
}
The repositorymethod() uses a select query to return an integer data from db.
For a positive scenario, I can Assert the return value. But the code coverage is still 60 percent for this method in NCover.
How do I test the Catch part of this method? How do I trigger the Exception part? Even if I give a negative value as input, 0 is returned which doesn't trigger the Exception.
This is a good scenario for mocking. If your repository is a separate class with an interface, you can use swap out your real repository for a mock which explicitly throws the exception.
Then:
There are many ways to inject this mock into your class. If you are using Dependency Injection containers such as Spring or MEF, they can be configured to inject mocks for your tests. The setter method shown above is only for demonstration purposes.