相关疑难解决方法(0)

ASP.NET MVC:使用UrlHelper的单元测试控制器

我的一个控制器操作,一个在Ajax请求中被调用,正在向客户端返回一个URL,以便它可以进行重定向.我正在使用Url.RouteUrl(..)并且在我的单元测试期间由于Controller.Url参数未预先填充而失败.

我尝试了很多东西,其中包括尝试存根UrlHelper(失败),手动创建一个UrlHelper带有RequestContext存根HttpContextBase(在RouteCollection.GetUrlWithApplicationPath调用时失败)的存根.

我搜索了谷歌,但几乎没有发现这个问题.我Url.RouteUrl在Controller操作中使用了一些非常愚蠢的东西吗?有没有更简单的方法?

更糟糕的是,我希望能够在我的单元测试中测试返回的URL - 实际上我只是想知道它重定向到正确的路由,但是因为我正在返回一个URL而不是一个URL route,我想控制解析的URL(例如,通过使用stubbed RouteCollection) - 但我很乐意让我的测试通过开始.

asp.net-mvc unit-testing urlhelper

170
推荐指数
3
解决办法
4万
查看次数

使用Request.CreateResponse进行ASP.NET WebApi单元测试

我正在尝试为我的ApiController编写一些单元测试并遇到一些问题.有一个很好的扩展方法叫做Request.CreateResponse,可以帮助生成响应.

public HttpResponseMessage Post(Product product)
{
  var createdProduct = repo.Add(product);
  return this.Request.CreateResponse(HttpStatusCode.Created, createdProduct);
}
Run Code Online (Sandbox Code Playgroud)

有没有办法在不使用部分模拟或直接使用"new HttpResponseMessage(...)"的情况下模拟CreateResponse?

c# unit-testing mocking httpresponse asp.net-web-api

144
推荐指数
3
解决办法
5万
查看次数

ASP.NET MVC控制器单元测试 - UrlHelper扩展问题

尝试在我的ASP.NET MVC 3 Web应用程序中进行一些控制器单元测试.

我的测试是这样的:

[TestMethod]
public void Ensure_CreateReviewHttpPostAction_RedirectsAppropriately()
{
   // Arrange.
   var newReview = CreateMockReview();

   // Act.
   var result = _controller.Create(newReview) as RedirectResult;

   // Assert.
   Assert.IsNotNull(result, "RedirectResult was not returned");
}
Run Code Online (Sandbox Code Playgroud)

很简单.基本上测试一个[HttpPost]动作以确保它返回一个RedirectResult(PRG模式).我没有使用,RedirectToRouteResult因为没有任何重载支持锚链接.继续.

现在,我正在使用Moq来模拟Http Context,包括服务器变量,控制器上下文,会话等.到目前为止一切顺利.

直到我在我的动作方法中击中了这一行:

return Redirect(Url.LandingPageWithAnchor(someObject.Uri, review.Uri);
Run Code Online (Sandbox Code Playgroud)

LandingPageWithAnchor 是一个自定义HTML帮助器:

public static string LandingPageWithAnchor(this UrlHelper helper, string uri1, string uri2)
{
   const string urlFormat = "{0}#{1}";

   return string.Format(urlFormat,
                helper.RouteUrl("Landing_Page", new { uri = uri1}),
                uri2);
}
Run Code Online (Sandbox Code Playgroud)

基本上,我重定向到另一个页面,这是新内容的"登陆页面",在新评论中有一个锚点.凉.

现在,这个方法之前失败了,因为它UrlHelper …

c# asp.net-mvc unit-testing moq asp.net-mvc-routing

15
推荐指数
1
解决办法
9073
查看次数