user2145263
user2145263

Reputation:

How to test Nullable paramenter passed to a function in ASP .Net MVC4 using Nunit Unit Testing

I have a method which looks like this.

public ActionResult Index(int ? page)
    {
        List<Request> reqList = re.DisplayAll();
        const int pageSize = 5;

        if (!string.Equals(Request.HttpMethod,"GET"))
        {
            page = 1;
        }

        int pageNumber = page ?? 1;

        return View(reqList.ToPagedList(pageNumber,pageSize));
    }

And my Test method looks like below.

 public void testReviewReturn()
      {

          var controller = CreateReviewController();
          var reviewResult = controller.Index(1);

          Assert.IsInstanceOf( typeof(ViewResult), reviewResult);
      }

Now when I pass 1 to Index function, it gives me an Exception that there is Null Reference Exception and the test fails. I'm not sure how to test this method. Need some advise. I'm new to Unit testing using Nunit as well as ASP .Net MVC4

Upvotes: 0

Views: 101

Answers (1)

Shyju
Shyju

Reputation: 218832

When you call the action method from your test project, Your Request will be null. So your If statement will throw an exception when running from the test project. Your code will work fine when you execute your action method using a browser.

What you should do is to mock the Request using some mocking frameworks. This answers shows how to do it with Moq.

Upvotes: 1

Related Questions