[英]Design MVC Controller using TDD for database calls
我是MVC和單元測試的新手。 我需要在控制器上進行單元測試,但恐怕我可能沒有正確設置它們。
例如:
public class MyController
{
public ActionResult Index(int id)
{
var locations = new MyLocations().GetLocations();
//linq code here that filters based on id
return View(filteredLocations)
}
}
這是一個非常簡單的示例,但是如何正確設置它,以便可以使用TDD模型,以便在進行單元測試時可以提供位置的靜態列表作為返回值?
我不確定應該如何正確地組織它。
由於new MyLocations()
緊密耦合意味着您將無法操縱其行為。
創建依賴關系的抽象
public interface ILocations {
IEnumerable<Location> GetLocations();
}
使實現從抽象派生
public class MyLocations : ILocations {
public IEnumerable<Location> GetLocations() {
//...db calls here
}
}
並重構控制器以依賴抽象
public class MyController : Controller {
private readonly ILocations myLocations;
public MyController(ILocations myLocations) {
this.myLocations = myLocations;
}
public ActionResult Index(int id) {
var locations = myLocations.GetLocations();
//linq code here that filters based on id
return View(filteredLocations);
}
}
現在可以對控制器進行測試,因為可以通過模擬框架或通過繼承進行隔離測試時,將替代品注入到控制器中。
在生產中,您將配置DependencyResolver
以將接口映射到實現,並將其注入到控制器中。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.