Jason
Jason

Reputation: 87

How to write C# unit test for proper code coverage in try catch block

I have the following code:

public class MyControllerClass : ApiController  
{  
   private readonly IManager _manager;

   public MyControllerClass(IManager manager)
   {
     this._manager = manager;
   }

   pubic async Task<IHttpActionResult> GetRequest()  
   {  
     try  
       {  
         await this._manager.GetRequest();  
         return this.ok();  
       }  
     catch (Exception ex)  
      {  
         this.logger.Error("Error message", ex);  
         throw this.HTTPResponseException("Request failed message", ex);   
      }   
   }
} 

public class ManagerFake : IManagerFake  
{  
    public Task GetRequest()  
    {  
        return Task.FromResult(true);  
    }  
}     

I am using NUnit for the unit testing. For the unit tests I have a FakeManager class registered in my IOC container which contains the GetResult() method and simply returns Task.FromResult(true) when executed. This allows the logic in the try block to be executed and thus proper code coverage is met for that section.

The problem I'm having is how do I create a test using the same FakeManager class that will throw an exception so that the catch block logic will be executed and code coverage is satisfied when there is no way to make two unique calls to the GetRequest() method since it doesn't take input parameters which could be used to distinguish the two different calls ?

Upvotes: 1

Views: 2356

Answers (2)

Wireless
Wireless

Reputation: 41

You probably want to look into mock framework (like Moq: https://github.com/Moq/moq4).

Instead of writing the ManagerFake class(es) that mimic all the behavior you are looking for you can simply mimic behavior:

var mock = new Mock<IManager>();
mock.Setup(manager => manager.GetRequest())
    .ReturnsAsync(true);

and

var mock = new Mock<IManager>();
mock.Setup(manager => manager.GetRequest())
    .Throws(new HTTPResponseException( ... ));

Upvotes: 4

Eric King
Eric King

Reputation: 11734

You don't use the same ManagerFake class that returns true. Make a different IManager implementation that throws an error.

Or, use a mock object library that will create mock object instances with exactly the behavior you want in each test.

Upvotes: 1

Related Questions