0

我有一个看起来像这样的方法。

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

我的测试方法如下所示。

 public void testReviewReturn()
      {

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

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

现在,当我将 1 传递给 Index 函数时,它给了我一个异常,即存在空引用异常并且测试失败。我不确定如何测试这种方法。需要一些建议。我是使用 Nunit 和 ASP .Net MVC4 进行单元测试的新手

4

1 回答 1

1

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.

于 2013-03-07T18:26:48.923 回答