1

I'm trying to write unit tests for a MVC application. im trying to test if my controller returns the correct view name.

This is the controller action im testing:

public IActionResult Index(string reportcode)
{
    if(string.IsNullOrEmpty(reportcode))
          ReportCode = reportcode;

     ViewBag.GridSource = GetReportData(reportcode);
     return View("Index");
}

This is my Unittest:

[Test]
public void Index_ReturnCorrectView()
{
    var controller = new HomeController();
    var result = controller.Index("COMD") as ViewResult;
    Assert.AreEqual("Index", result.ViewName); 
}

The error i get from the unit test is expected "Index" but got null. I did a lot of search and most answers say the ViewName property should be set after you declare it when returning the view. I tried the same but it wont work still.

Thank you

Power Star
  • 1,724
  • 2
  • 13
  • 25
7uner
  • 13
  • 5

1 Answers1

5

The documentation for Controller.View() states:

This method overload of the View class returns a ViewResult object that has an empty ViewName property. If you are writing unit tests for controller actions, take into account the empty ViewName property for unit tests that do not take a string view name.

At run time, if the ViewName property is empty, the current action name is used in place of the ViewName property.

So when expecting a view with the same name as the current action we can just test that it's an empty string.

Alternatively, the Controller.View(ViewName, Model) method will set the ViewName.

My Controller Method

    public ActionResult Index()
    {
      return View("Index");
    }

Test Method

    [TestMethod]
    public void Index()
    {
        // Arrange
        HomeController controller = new HomeController();

        // Act
        ViewResult result = controller.Index() as ViewResult;

        // Assert
        Assert.IsTrue(result.ViewName == "Index");
    }
Power Star
  • 1,724
  • 2
  • 13
  • 25
  • Controller.View(String) is exactly what OP is using – Andrei Aug 16 '17 at 17:44
  • @Andrei OP have to use like Controller.View("Index", "COMD") – Power Star Aug 16 '17 at 17:46
  • @PowerStar Hi thank you for the reply. Im not really sure what you mean by Controller.View("Index", "COMD"). Is this what i shoud return in the index method? I dont see how it's different from my current implementation since there is no need to return "COMD" – 7uner Aug 16 '17 at 17:54
  • @PowerStar alright so this passed the test! However I am still a bit confused. Does this actually call the index method from my controller? it seems to me its just creating a new view object with name index, if so it defeats the purpose of unit-testing – 7uner Aug 16 '17 at 18:01
  • @7uner I am getting expected value in my test controller – Power Star Aug 16 '17 at 18:15