2016-12-15 64 views
0

單元測試中我僞裝使用嘲諷控制器上下文和UrlHelper

var fakeHttpContext = new Mock<HttpContextBase>(); 
var controllerContext = new Mock<ControllerContext>(); 
controllerContext.Setup(t => t.HttpContext).Returns(fakeHttpContext.Object);    
this.controller.ControllerContext = controllerContext.Object; 

以下

UrlHelper helper = new UrlHelper(this.ControllerContext.RequestContext);       
string url = helper.Action("Details", "Pers", new { id = person.Id }); 

我應該怎麼單元測試裏面嘲笑爲了HTTP上下文現在我的代碼中我使用使用UrlHelper代碼? 當前UrlHelper助手爲null。

p.s.由於清晰,我沒有在測試中顯示控制器代碼的完整初始化,它正在工作,但我現在正在努力處理這個請求上下文和UrlHelper。

+0

控制器已經有一個'UrlHelper Url'屬性,您可以傳遞一個實例或模擬。代碼中不需要新的代碼。 – Nkosi

+0

所以,我錯過了控制器上下文設置內的東西? – user1765862

+0

你錯過了控制器中的東西。 – Nkosi

回答

0

Controller已經有UrlHelper Url屬性,您可以傳遞實例或模擬。代碼中不需要新的代碼。

看看這個使用UrlHelper控制器的示例測試。

[TestClass] 
public class UrlHelperTest { 
    [TestMethod] 
    public void MockUrlHelper() { 
     //Arrange 
     var requestUrl = new Uri("http://myrequesturl"); 
     var request = Mock.Of<HttpRequestBase>(); 
     var requestMock = Mock.Get(request); 
     requestMock.Setup(m => m.Url).Returns(requestUrl); 

     var httpcontext = Mock.Of<HttpContextBase>(); 
     var httpcontextSetup = Mock.Get(httpcontext); 
     httpcontextSetup.Setup(m => m.Request).Returns(request); 


     var actionName = "MyTargetActionName"; 
     var expectedUrl = "http://myfakeactionurl.com"; 
     var mockUrlHelper = new Mock<UrlHelper>(); 
     mockUrlHelper 
      .Setup(m => m.Action(actionName, "Register", It.IsAny<object>(), It.IsAny<string>())) 
      .Returns(expectedUrl) 
      .Verifiable(); 

     var sut = new MyController(); 
     sut.Url = mockUrlHelper.Object; 
     sut.ControllerContext = new ControllerContext { 
      Controller = sut, 
      HttpContext = httpcontext, 
     }; 

     //Act 
     var result = sut.MyAction(); 

     //Assert 
     mockUrlHelper.Verify(); 
    } 

    public class MyController : Controller { 
     [HttpPost] 
     public ActionResult MyAction() { 
      var link = GenerateActionLink("MyTargetActionName", string.Empty, string.Empty); 

      return View((object)link); 
     } 

     private string GenerateActionLink(string actionName, string token, string username) { 
      string validationLink = null; 
      if (Request.Url != null) { 
       var encodedToken = EncodedUrlParameter(token); 
       var url = Url.Action(actionName, "Register", new { Token = encodedToken, Username = username }, Request.Url.Scheme); 
       validationLink = url; 
      } 

      return validationLink; 
     } 

     private string EncodedUrlParameter(string token) { 
      return "Fake encoding"; 
     } 

    } 
}