asp.net-mvc-3 - 为什么单元测试使用 mstest 命令行失败,但在 VS2010 Professional 中却没有?

标签 asp.net-mvc-3 unit-testing

我对 asp.net mvc3 应用程序的单元测试有一点问题。

如果我在 Visual Studio 2010 Professional 中运行一些单元测试,它们已成功通过。

如果我使用 Visual Studio 2010 Professional 命令行

mstest /testcontainer:MyDLL.dll /detail:errormessage /resultsfile:"D:\A Folder\res.trx"

然后出现错误:

[errormessage] = Test method MyDLL.AController.IndexTest threw exception:
System.NullReferenceException: Object reference not set to an instance of an object.

我的 Controller :

public ActionResult Index(){
   RedirectToAction("AnotherView");
}

并在测试

AController myController = new AController();
var result = (RedirectToRouteResult)myController.Index();

Assert.AreEqual("AnotherView", result.RouteValues["action"]);

如何解决这个问题以在两种情况下(VS2010 和 mstest.exe)正常工作?

谢谢

PS:我读了Test run errors with MSTest in VS2010但如果我有 VS2010 Ultimate/Premium,那可以解决。

最佳答案

我发现了问题。问题是 AnotherView 操作。

AnotherView 包含的操作

private AModel _aModel;

public ActionResult AnotherView(){
  // call here the function which connect to a model and this connect to a DB

  _aModel.GetList();
  return View("AnotherView", _aModel);
}

需要做什么:

1.制作一个带参数的 Controller 构造函数

public AController(AModel model){
  _aModel = model;
}

2.在测试或单元测试类中,创建一个模拟

public class MockClass: AModel
{

  public bool GetList(){  //overload this method
     return true;
  }

  // put another function(s) which use(s) another connection to DB
}

3.在当前的测试方法IndexTest

[TestMethod]
public void IndexTest(){
   AController myController = new AController(new MockClass());
   var result = (RedirectToRouteResult)myController.Index();

   Assert.AreEqual("AnotherView", result.RouteValues["action"]);
}

现在单元测试可以运行了。不适用于集成测试。在那里你必须提供连接到数据库的配置并且不应用模拟,只需使用我的问题中的代码。

经过 5-6 小时的研究,希望这对您有所帮助 :)

关于asp.net-mvc-3 - 为什么单元测试使用 mstest 命令行失败,但在 VS2010 Professional 中却没有?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12859172/

相关文章:

jquery - 将 ASP.NET MVC 3 ViewModel 渲染为 ListView、Accordian 或 Razor View 中的简单列表

unit-testing - 如何在 SSDT 单元测试中部署数据但仅用于单元测试

unit-testing - 如何使用内存中的 Derby 数据库进行 Hive (Scala) 测试

android - 模拟 java.lang.AssertionError : Verification failed: call 1 of 1: was not called

javascript - 在 Javascript 中访问 Razor bool 变量时出错

asp.net-mvc-3 - ASP.NET MVC 3 动态控件和非侵入式验证

asp.net-mvc-3 - 将@helper 代码转移到 App_Code 文件夹抛出错误

c# - 测试函数 "System.Web.Mvc.ViewEngines.Engines.FindPartialView"

unit-testing - 如何更改单元测试模块中的 Perl Readonly 标量?

javascript - 未定义不是函数: unit testing passport authentication custom callback