简体   繁体   中英

Unit Testing ViewResult in Asp.NET MVC

Even though there are couple of Posts on StackOverflow about Unit Testing Action Result in MVC, I have a specific Question ....

Here is my ActionResult in Controller:

public ActionResult Index()
{
    return View(db.Products.ToList());
}

Every Item in Products has different attributes like Name,Photo,Quantity etc.. I wrote a testmethod for this method .It looks as follows :

private CartEntity db = new CartEntity();

[TestMethod]
public void Test_Index()
{
    //Arrange
    ProductsController prodController = new ProductsController();

    ViewResult = prodController.Index();


}

What Should I compare in this case since there are no parameters are being passed into Index Action

Check out the ViewResult class, this can show you what else you could test. What you need to do is mock your DbContext and supply it with data in the Products property ( DbSet<> ) as this is being called in your controller's action. You can then test

  1. The type being returned
  2. The model on the ViewResult
  3. The ViewName which should be empty or Index

Sample code

[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");
}

If you need help mocking a DbContext there are existing frameworks and articles on this subject. Here is one from Microsoft titled Testing with a mocking framework . Ideally you should be injecting your dependencies (including DbContext instances) into the constructors of your Controller instances using a DI framework like AutoFac or Unity or NInject (the list goes on). This also makes unit testing much easier.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM