0

This is my method..

public ActionResult PowerTrainConditionReview()
    {
        ViewData["id"] = RouteData.Values["id"];
        return View();
    }

How should i write a unit test for return view when the method contains Viewdata in it...?

I tried something like this

 [Test]
    public void ShouldRenderPowerTrainConditionReview()
    {

        sut.WithCallTo(x => x.PowerTrainConditionReview()).ShouldRenderDefaultView();
    }

System.NullReferenceException : Object reference not set to an instance of an object.

before return view statement this exception is thrown

  • provide the controller with the necessary dependencies in order for the test to be exercised to completion. – Nkosi Apr 02 '18 at 11:28
  • @Nkosi how should i include ViewData["id"] = RouteData.Values["id"]; this statement in my unit test –  Apr 02 '18 at 11:39
  • Look into creating a `ControllerContext` and assign that to the controller. That is where the route data is coming from. – Nkosi Apr 02 '18 at 11:43
  • Can you explain more about the above comment –  Apr 03 '18 at 04:12

1 Answers1

0

Hmm, you shouldn't actually unittest a view/action method since there is nothing to test there. For example, in your posted code the RouteData isn't actually present unless you run the application and get into MVC pipeline. So you can't test it and mocking it would also be difficult. Rather test the business layer unit(s).

In case you have the logic in action method itself then that's against what MS or other recommends and you should refactor your code.

Rahul
  • 71,392
  • 13
  • 57
  • 105
  • @ rahul but i used check whether the method returns the defaultview..and it used to work this time due to ViewData["id"] = RouteData.Values["id"]; this statement is not possible How should i use this statement in my unit test? –  Apr 02 '18 at 11:42