gpt4 book ai didi

c# - 模拟 Controller 上下文和 UrlHelper

转载 作者:行者123 更新时间:2023-11-30 21:43:58 25 4
gpt4 key购买 nike

在单元测试中,我正在使用

伪造 http 上下文
 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 });

为了使用 UrlHelper 代码,我应该在单元测试中模拟什么?当前 UrlHelper 帮助器为空。

附注为了清楚起见,我没有在测试中展示 Controller 代码的完整初始化,它正在工作,但我现在正在努力处理这个请求上下文和 UrlHelper。

最佳答案

Controller 已经有一个 UrlHelper Url 属性,您可以传递一个实例或模拟。无需在代码中新建一个。

使用使用 UrlHelper 的 Controller 查看此示例测试。

[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";
}

}
}

关于c# - 模拟 Controller 上下文和 UrlHelper,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41166107/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com