asp.net mvc 3 - How to test WebAPI Controllers? -


i have webapi application has repository layer, dto service layer, , webapi layer. webapi calls dto calls repository.

my repository begins this:

public class repositoryservice : irepositoryservice     {         private readonly dbcontext _db;          public repositoryservice(string connectionstring)         {             _db = new dbcontext(connectionstring);         }          public repositoryservice()         {             _db = new dbcontext();         } 

and dto service begins this:

public class dtoservice : idtoservice     {         private readonly repositoryservice _repository;          public dtoservice(string connectionstring)         {             _repository = new repositoryservice(connectionstring);           }          public dtoservice()         {             _repository = new repositoryservice();            } 

my dbcontext looks this:

public dbcontext() : base("name=testconnection")         {          }  public dbcontext(string connectionstring) : base(connectionstring)         {          } 

this, far, has allowed me optionally define connection string use when running application tests.

first question: approach seem ok?

now i'm webapi layer, don't have single controller class. have bunch of different controllers. i'm thinking going through , implementing these constructors each of controllers, there's gotta better way this. tells me dependency injection comes play, i'm not sure.

i this:

  1. create constructors each controller have services above
  2. in test, new instance of each controller

    var accountcontroller = new accountcontroller(connectionstringfortesting)

but know not practical, so...

second question: practical approach like?

if interested in unit tests, it's practice mock database, tests not rely on kind of io or database. may want hide dbcontext behind interface , use mocking framework (moq instance) mock requests' callbacks instead of passing connection string.

if interested in integration testing, you'll need separate database , code can remains same.


Comments