gpt4 book ai didi

asp.net-mvc - 如何测试 ASP.NET MVC 路由重定向到其他站点?

转载 作者:行者123 更新时间:2023-12-04 15:04:57 25 4
gpt4 key购买 nike

由于某些宣传 Material 中的打印错误,我有一个站点正在接收大量请求,这些请求应该是一个站点到达另一个站点。
IE。
有效站点是 http://site1.com/abc & http://site2.com/def但人们被告知去http://site1.com/def .

我可以控制site1,但不能控制site2。

site1 包含用于检查路由的第一部分在 actionfilter 中是否有效的逻辑,如下所示:

public override void OnActionExecuting(ActionExecutingContext filterContext)
{
base.OnActionExecuting(filterContext);

if ((!filterContext.ActionParameters.ContainsKey("id"))
|| (!manager.WhiteLabelExists(filterContext.ActionParameters["id"].ToString())))
{
if (filterContext.ActionParameters["id"].ToString().ToLowerInvariant().Equals("def"))
{
filterContext.HttpContext.Response.Redirect("http://site2.com/def", true);
}

filterContext.Result = new ViewResult { ViewName = "NoWhiteLabel" };
filterContext.HttpContext.Response.Clear();
}
}

我不确定如何测试重定向到另一个站点。
我已经有使用 MvcContrib 测试助手重定向到“NoWhiteLabel”的测试,但是这些无法处理(据我所知)这种情况。

如何测试重定向到另一个站点?

最佳答案

我建议您使用 RedirectResult而不是调用 Response.Redirect :

if (youWantToRedirect) 
{
filterContext.Result = new RedirectResult("http://site2.com/def")
}
else
{
filterContext.Result = new ViewResult { ViewName = "NoWhiteLabel" };
}

现在,如果您知道如何测试 ViewResult与 MVCContrib TestHelper您将能够测试 RedirectResult一样的方法。棘手的部分是 mock manager强制它满足 if 条件。

更新:

以下是示例测试的样子:
    // arrange
var mock = new MockRepository();
var controller = mock.StrictMock<Controller>();
new TestControllerBuilder().InitializeController(controller);
var sut = new MyFilter();
var aec = new ActionExecutingContext(
controller.ControllerContext,
mock.StrictMock<ActionDescriptor>(),
new Dictionary<string, object>());

// act
sut.OnActionExecuting(aec);

// assert
aec.Result.ShouldBe<RedirectResult>("");
var result = (RedirectResult)aec.Result;
result.Url.ShouldEqual("http://site2.com/def", "");

更新(由马特莱西)
以下是我实际得到这个工作的方式:
    // arrange
var mock = new MockRepository();
// Note that in the next line I create an actual instance of my real controller - couldn't get a mock to work correctly
var controller = new HomeController(new Stubs.BlankContextInfoProvider(), new Stubs.BlankWhiteLabelManager());
new TestControllerBuilder().InitializeController(controller);
var sut = new UseBrandedViewModelAttribute(new Stubs.BlankWhiteLabelManager());

var aec = new ActionExecutingContext(
controller.ControllerContext,
mock.StrictMock<ActionDescriptor>(),
// being sure to specify the necessary action parameters
new Dictionary<string, object> { { "id", "def" } });

// act
sut.OnActionExecuting(aec);

// assert
aec.Result.ShouldBe<RedirectResult>("");
var result = (RedirectResult)aec.Result;
result.Url.ShouldEqual("http://site2.com/def", "");

关于asp.net-mvc - 如何测试 ASP.NET MVC 路由重定向到其他站点?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2453618/

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