我对 mvc3 应用程序的 UnitTests 有一点问题 asp.net。
如果我在Visual Studio 2010 Professional中运行一些单元测试,它们已成功通过。
如果我使用 Visual Studio 2010 Professional 命令行
mstest /testcontainer:MyDLL.dll /detail:errormessage /resultsfile:"D:A Folderres.trx"
然后发生了错误:
[errormessage] = Test method MyDLL.AController.IndexTest threw exception:
System.NullReferenceException: Object reference not set to an instance of an object.
和我的控制器:
public ActionResult Index(){
RedirectToAction("AnotherView");
}
并在测试中
AController myController = new AController();
var result = (RedirectToRouteResult)myController.Index();
Assert.AreEqual("AnotherView", result.RouteValues["action"]);
如何解决此问题以在两种情况下正常工作(VS2010和mstest.exe)?
谢谢
PS:我在VS2010中阅读了MSTest的测试运行错误,但是如果我有VS2010旗舰版/高级版,则可以解决。
我发现了问题。问题在于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.制作一个参数为控制器构造函数
public AController(AModel model){
_aModel = model;
}
2.In 测试或单元测试类中,创建一个模拟类,例如
public class MockClass: AModel
{
public bool GetList(){ //overload this method
return true;
}
// put another function(s) which use(s) another connection to DB
}
3.In 当前测试方法 索引测试
[TestMethod]
public void IndexTest(){
AController myController = new AController(new MockClass());
var result = (RedirectToRouteResult)myController.Index();
Assert.AreEqual("AnotherView", result.RouteValues["action"]);
}
现在单元测试将起作用。不适用于集成测试。在那里,您必须提供与数据库连接的配置,并且不要应用模拟,只需使用我问题中的代码即可。
在研究 5-6 小时后希望这有所帮助:)