【问题标题】:Unit testing MVC routes that POST单元测试 POST 的 MVC 路由
【发布时间】:2009-06-15 02:50:45
【问题描述】:

我有 2 条路线注册如下:

routes.MapRoute("GetAnEmail", "{controller}", new { controller = "Home", action = "GetAnEmail" }, new { httpMethod = new HttpMethodConstraint("POST") })
routes.MapRoute("Home", "{controller}/{action}", new { controller = "Home", action = "Index" })

我对 Home 控制器进行了有效的单元测试,如下所示:

 [Test]
 public void CanVerifyRouteMaps()
     {
         "~/".Route().ShouldMapTo<HomeController>(x => x.Index());
     }

我知道 GetAnEmail 有效,但如何用一个单元测试 POSTed 路由?

【问题讨论】:

    标签: asp.net-mvc unit-testing routes mvccontrib


    【解决方案1】:

    Gratzy 的回答很接近,但向我展示的只是如何通过代码进行 POST。

    我认为Stephen Walther's blog post 中暗示了解决方案。我真的在这里测试我的路线约束,这是关键。 Stephen 在他的示例中创建了一个假的 httpContext。我将尝试使用 Rhino Mocks 进行此操作,一旦我有一个可行的示例,我会回复。如果有人已经使用 Rhino Mock 或 Moq 完成此操作,请也发布。

    【讨论】:

      【解决方案2】:

      您需要在单元测试中模拟一个帖子。

      System.Net.WebRequest req = System.Net.WebRequest.Create("your url");
      
      req.ContentType = "text/xml";
      req.Method = "POST";
      
      byte[] bytes = System.Text.Encoding.ASCII.GetBytes("Your Data");
      req.ContentLength = bytes.Length;
      os = req.GetRequestStream();
      os.Write(bytes, 0, bytes.Length); 
      
      
      System.Net.WebResponse resp = req.GetResponse();
      if (resp == null) return;
      System.IO.StreamReader sr = new System.IO.StreamReader(resp.GetResponseStream());
      
      str responsecontent = sr.ReadToEnd().Trim();
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2013-04-06
        • 2020-08-15
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2014-01-14
        • 2018-11-09
        相关资源
        最近更新 更多