2011-09-06 63 views
1

基本上我想设置20个左右的Request.Form值,发送POST到我的控制器,然后检查结果。编写将Request.Form数据发送到我的控制器的单元测试最简单的方法是什么?

我发现了几篇文章,如this one,它们描述了如何使用NUnit,MVCContrib和Rhino Mocks的组合来完成此操作。但我不知道这是否真的有必要。

似乎Visual Studio 2010和ASP.NET MVC 2应该能够在本地执行此操作,并在“测试结果”窗口中显示结果。事实上,当我创建的向导创建新的单元测试,谈到了这个...

[TestMethod()] 
[HostType("ASP.NET")] 
[AspNetDevelopmentServerHost("G:\\Webs\\MyWebsite.com\\MyWebsite", "/")] 
[UrlToTest("http://localhost:43383/")] 
public void PaypalIPNTest() 
{ 
    BuyController target = new BuyController(); // TODO: Initialize to an appropriate value 
    ActionResult expected = new EmptyResult(); // TODO: Initialize to an appropriate value 
    ActionResult actual; 
    actual = target.PaypalIPN(); 
    Assert.AreEqual(expected, actual); 
    Assert.Inconclusive("Verify the correctness of this test method."); 
} 

是否有可能根据上面的代码养活target.PaypalIPN()我的Request.Form变量?还是我需要依靠第三方库来完成这个任务?

回答

3

事实上,当我创建的向导创建新的单元测试,谈到了这个

是,和所有你可以保持距离,这是方法签名。方法体是无用的。

因此,让我们通过观察此开始:

是否可以养活target.PaypalIPN()我的Request.Form变量

通过阅读这句话我认为你的控制器动作看起来是这样的:

[HttpPost] 
public ActionResult PaypalIPN() 
{ 
    string foo = Request["foo"]; 
    string bar = Request["bar"]; 
    ... do something with foo and bar 
} 

所以第一个是通过引入视图模型来改善这个代码:

public class MyViewModel 
{ 
    public string Foo { get; set; } 
    public string Bar { get; set; } 
} 

,然后修改你的方法签名:

[HttpPost] 
public ActionResult PaypalIPN(MyViewModel model) 
{ 
    ... do something with model.Foo and model.Bar 
} 

现在你的控制器是由任何HttpContext的基础设施代码(这确实应该留给框架抽象,它不是你的控制器的行为负责阅读请求参数=>这是管道代码)和单元测试是多么简单的事:

[TestMethod()] 
public void PaypalIPNTest() 
{ 
    // arrange 
    var sut = new BuyController(); 
    var model = new MyViewModel 
    { 
     Foo = "some foo", 
     Bar = "some bar", 
    }; 

    // act 
    var actual = sut.PaypalIPN(model); 

    // assert 
    // TODO: 
} 

OK,这是说,在这里,我们处理了一些非常简单的控制器动作。对于更高级的场景,你应该考虑使用模拟框架。我个人使用MvcContrib.TestHelper与Rhino Mocks来测试我的ASP.NET MVC应用程序。

+0

谢谢你。我忘了模型可以被MVC引擎自动解释为表单集合。这样做肯定会清理PaypalIPN功能。 –

0

我有另一种方法来测试我的MVC应用程序,首先我使用Dev Magic Fake来伪造控制器下的任何下划线层,直到应用程序正在运行并且业务被批准为止,然后使用基于TDD方法替换伪代码批准要求

CodePlex上

见开发魔术假:

http://devmagicfake.codeplex.com/

感谢

M.Radwan

相关问题