Url.动作在JSON字符串中变为空



对测试有点陌生,所以请原谅我,

我有一个控制器,它返回一个包含Url计算字符串的JsonResult。像这样的操作:

 public ActionResult GetResult(SomeModel model)
 {
     if (ModelState.IsValid)
     {
         return Json(new { redirectTo = Url.Action("Index", "Profile") });
     }
 }

当我使用jQuery使用结果时,应用程序工作得很好。

然而,在我的单元测试中,我有问题,因为当我测试Json字符串的内容时,redirectTo值似乎是"null",即使它在应用程序本身不是null。

我的测试方法看起来像这样:

 [Test]
 public void GetResult_Success()
 {
     var result = controller.GetResult(new SomeModel());
     Assert.IsNotNull(result);
     Assert.IsInstanceOf<JsonResult>(result);
     var jsonResult = result as JsonResult;
     var jsonObject = JsonConvert.DeserializeAnonymousType(new JavaScriptSerializer().Serialize(jsonResult.Data), new
     {
         redirectTo = string.Empty
     });
     Assert.AreEqual("Profile/Index", jsonObject.redirectTo);
 }

这个失败是因为jsonObject。redirectTo为空。如果我在控制器中改变Url。操作进入"概要文件/索引",测试通过。然而Url。Action("Index", "Profile")失败,因为它只在单元测试中变为null。

如果我尝试在上下文设置中为测试设置路由值,它会抱怨它们已经注册了。我用的是Moq。知道我需要设置什么吗?提前致谢

答案在此链接

为了更持久而复制的代码:

public static void SetupWithHttpContextAndUrlHelper(this Controller controller)
{
    var routes = new RouteCollection();
    MvcApplication.RegisterRoutes(routes);
    //setup request
    var requestContextMock = new Mock<HttpRequestBase>();
    requestContextMock.Setup(r => r.AppRelativeCurrentExecutionFilePath).Returns("/");
    requestContextMock.Setup(r => r.ApplicationPath).Returns("/");
    //setup response
    var responseMock = new Mock<HttpResponseBase>();
    responseMock.Setup(s => s.ApplyAppPathModifier(It.IsAny<string>())).Returns<string>(s => s);
    //setup context with request and response
    var httpContextMock = new Mock<HttpContextBase>();
    httpContextMock.Setup(h => h.Request).Returns(requestContextMock.Object);
    httpContextMock.Setup(h => h.Response).Returns(responseMock.Object);
    controller.ControllerContext = new ControllerContext(httpContextMock.Object, new RouteData(), controller);
    controller.Url = new UrlHelper(new RequestContext(httpContextMock.Object, new RouteData()), routes);
}

相关内容

  • 没有找到相关文章

最新更新