尽管 StackOverflow 上有几篇关于 MVC 中的单元测试操作结果的帖子,但我有一个具体的问题....
这是我在 Controller 中的 ActionResult:
public ActionResult Index()
{
return View(db.Products.ToList());
}
产品中的每个项目都有不同的属性,如名称、照片、数量等。 我为这个方法写了一个测试方法。它看起来如下:
private CartEntity db = new CartEntity();
[TestMethod]
public void Test_Index()
{
//Arrange
ProductsController prodController = new ProductsController();
ViewResult = prodController.Index();
}
在这种情况下,我应该比较什么,因为没有参数被传递到索引操作中
最佳答案
查看 ViewResult类,这可以告诉你你还可以测试什么。
你需要做的是模拟你的 DbContext
并在 Products
中提供数据属性 ( DbSet<>
),因为它在您的 Controller 的操作中被调用。
然后你可以测试
- 返回的类型
- ViewResult 上的模型
- 应为空或索引的 ViewName
示例代码
[TestMethod]
public void Test_Index()
{
//Arrange
ProductsController prodController = new ProductsController(); // you should mock your DbContext and pass that in
// Act
var result = prodController.Index() as ViewResult;
// Assert
Assert.IsNotNull(result);
Assert.IsNotNull(result.Model); // add additional checks on the Model
Assert.IsTrue(string.IsNullOrEmpty(result.ViewName) || result.ViewName == "Index");
}
如果您在模拟 DbContext 方面需要帮助,可以找到有关此主题的现有框架和文章。这是来自 Microsoft 的一个标题为 Testing with a mocking framework .理想情况下,您应该将依赖项(包括 DbContext 实例)注入(inject) Controller
的构造函数中使用 DI 框架的实例,如 AutoFac 或 Unity 或 NInject(不胜枚举)。这也使单元测试更加容易。
关于c# - Asp.NET MVC 中的单元测试 ViewResult,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36897046/