Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 470
sujay kodamala Avatar asked Apr 27 '16 17:04

sujay kodamala


1 Answers

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.

like image 180
Igor Avatar answered Nov 07 '22 21:11

Igor