我对 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/