2013-05-06 84 views
0

我有一個webAPI應用程序,它有一個存儲庫層,DTO服務層和WebAPI層。 WebAPI調用DTO調用Repository。如何測試WebAPI控制器?

我的倉庫是這樣開始的:

public class RepositoryService : IRepositoryService 
    { 
     private readonly DbContext _db; 

     public RepositoryService(string connectionString) 
     { 
      _db = new DbContext(connectionString); 
     } 

     public RepositoryService() 
     { 
      _db = new DbContext(); 
     } 

我的DTO服務是這樣開始的:

public class DtoService : IDtoService 
    { 
     private readonly RepositoryService _repository; 

     public DtoService(string connectionString) 
     { 
      _repository = new RepositoryService(connectionString); 
     } 

     public DtoService() 
     { 
      _repository = new RepositoryService(); 
     } 

我的DbContext看起來是這樣的:

public DbContext() : base("name=TestConnection") 
     { 

     } 

public DbContext(string connectionString) : base(connectionString) 
     { 

     } 

此,到目前爲止,允許我可選地定義一個連接字符串,以便在運行測試應用程序時使用。

第一個問題:這種方法看起來好嗎?

現在,我到我的WebAPI層,我不只有一個控制器類。我有一堆不同的控制器。我正在考慮爲每個控制器執行這些構造函數,但是有一個更好的方法可以做到這一點。有些東西告訴我這是依賴注入的地方,但我不確定。

我可以做這樣的事情:

  1. 爲每個控制器構造像我有我的服務上面
  2. 在我的測試中,新的像

    VAR每個控制器的一個實例accountController = new AccountController(connectionStringForTesting)

但我知道這是不實用,所以...

第二個問題:實際方法是什麼樣子?

回答

1

如果您對單元測試感興趣,那麼最好模擬一個數據庫,這樣您的測試就不會依賴於任何類型的IO或數據庫。您可能希望在接口後面隱藏您的DBContext,並使用任何模擬框架(例如Moq)來模擬請求的回調,而不是傳遞連接字符串。

如果您對集成測試感興趣,那麼您只需要單獨的數據庫,並且所有代碼都可以保持不變。

0

爲了讓你的類很好地進行單元測試,注入所有的依賴關係是一個很好的習慣,這樣你就可以獨立地測試每一個類。

下面這樣做 - 它不會開箱即用,因爲您需要連接所選容器中的依賴關係,並且配置可能會因所處位置的不同而有所不同但是我希望你能明白這一點。

public DbContext(IConfig config) : base(config.ConnectionString) 
{ 
} 

public interface IConfig 
{ 
    string ConnectionString {get;} 
} 

public class RepositoryService : IRepositoryService 
{ 
    private readonly DbContext _dbContext; 

    public RepositoryService(IDbContext dbContext) 
    { 
     _dbContext = dbContext; 
    } 
} 

public class DtoService : IDtoService 
    { 
     private readonly RepositoryService _repository; 

     public DtoService(IRepositoryService repository) 
     { 
     } 
} 

在做完所有這些之後,您會使用Dima建議的模擬框架 - 在Rhino中。嘲笑你會沿着這些線路去做點什麼:

var config = MockRepository.GenerateStub<IConfig>(); 
config.Stub(c => c.ConnectionString).Return("yourConnectionString"); 

var dbContext = MockRepository<IDbContext>(); 

var controller = new YourController([mockDependency1], [mockDependency2]); 

controller.[YourMethod](); 
_dbContext.AssertWasCalled(dc => dc.[theMEthodYouExpectToHaveBeenCalled])