2015-05-06 82 views
0

我有這個功能和單元測試。如何對這個.net MVC函數進行單元測試?

ProfileController可代碼

[HttpPost] 
public ActionResult Edit(int? id) 
{ 
    var redirectUrl = new UrlHelper(Request.RequestContext).Action("Index", "Profile", new { id = 0 }); 
    return Json(new { Url = redirectUrl }); 
} 

單元測試代碼

[TestMethod] 
public void TestDetailsViewData() 
{ 
    var controller = new ProfileController(_Profile); 

    var result = controller.Edit(1) as ViewResult; 
    var profile = (VIEWMODELS.Customer.Profile)result.ViewData.Model; 
    Assert.AreEqual("Testor", profile.cardName); 
} 

我想測試這個功能,這個功能會重定向到索引頁,並返回數據的ViewPage。但問題是,因爲請求當我運行這個單元測試代碼,我在這行了空例外,是NULL

var redirectUrl = new UrlHelper(Request.RequestContext).Action("Index", "Profile", new { id = 0 }); 

,可能我知道我怎麼能考這個?

已更新,起訂量功能 經過進一步的閱讀,並從here一些示例代碼,它似乎要求能夠充滿價值,但現在的RequestContext是NULL,任何人都可以點我到正確的地方爲我學習?

[TestMethod] 
     public void TestDetailsViewData() 
     { 
      var request = new Mock<HttpRequestBase>(); 
      request.SetupGet(x => x.Headers).Returns(
       new System.Net.WebHeaderCollection { 
       {"X-Requested-With", "XMLHttpRequest"} 
      }); 

      var context = new Mock<HttpContextBase>(); 
      context.SetupGet(x => x.Request).Returns(request.Object); 
      //context.SetupGet(x => x.Request.RequestContext).Returns(request.Object.RequestContext); 

      var controller = new ProfileController(_Profile); 
      controller.ControllerContext = new ControllerContext(context.Object, new RouteData(), controller); 
      controller.Request.RequestContext = context.Object.Request.RequestContext; 
      var result = controller.Edit(1) as ViewResult; 
      var profile = (VIEWMODELS.Customer.Profile)result.ViewData.Model; 
      Assert.AreEqual("testor", profile.cardName); 
     } 

回答

相關問題