在单元测试中模拟以下代码的最佳方法是什么:
public ActionResult Products()
{
ViewBag.Title = "Company Product";
IEnumerable<ProductDetailDto> productList = ProductService.GetAllEffectiveProductDetails();
ProductModels.ProductCategoryListModel model = new ProductModels.ProductCategoryListModel
{
//the type of ProductDetails => IEnumerable<productDetailDto>
ProductDetails = ProductService.GetAllEffectiveProductDetails(),
//the type of ProductCategoryList => IEnumerable<selectlistitem>
ProductCategoryList = productList.Select(x => new SelectListItem
{
Value = x.FKProductId.ToString(),
Text = x.Name
})
};
return View(model);
}
Run Code Online (Sandbox Code Playgroud)
仅供参考,我正在开发VS 2012,MVC 4.0,使用MOQ对象进行单元测试和TFS设置.
任何人都可以帮我解决这个问题,对于上述方法,使用模拟对象的最佳测试方法是什么?
我在这篇文章中读到他们正在使用依赖注入来在每个mvc请求上加载存储库实例.
我不确定我是否理解正确,但我目前在我的mvc应用程序中使用.UserRepository它实现了IUserRepository接口.此接口注入控制器构造函数
public class UserController : Controller
{
private IUserRepository repository;
public UserController(IUserRepository rep)
{ repository = rep; }
public UserController() : this(new UserRepository()) {}
}
Run Code Online (Sandbox Code Playgroud)
但我没有看到使用这个接口的任何好处(IUserRepository)我可以使用UserRepository没有接口.显然有人认为这是正确的方法(我已经在apress mvc4书上找到了它)我会请求有人详细说明为什么这是更好的方法而不是使用没有接口的存储库.
考虑到这一点,我会请任何人分享有关如何实现此方法的具体示例或链接(使用依赖注入来在每个mvc请求上加载存储库实例).