0
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.

package
  • 4,741
  • 1
  • 25
  • 35
user1890098
  • 473
  • 2
  • 10
  • 24

1 Answers1

5

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.

// Interface instead of concrete class
IRepository repository;
...

// Some way to inject a mock repo.
public void SetRepository(IRepository repo)
{
    this.repository = repo;
}

public int ReturnFromDB(int input)
{
    try
    {
         return repository.method(input);
    }
    catch(RepositoryException ex)
    {
         throw new ParticularException("some message",ex);
    }
}

Then:

public class MockRepo : IRepository
{
    public int method(int input)
    {
        throw new RepositoryException();
    }
}

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.

metacubed
  • 7,031
  • 6
  • 36
  • 65
  • I'd leave out the setter and use a constructor parameter. Simpler AND cleaner. Otherwise I agree completely. – EagleBeak Jun 05 '14 at 11:48