2012-10-12 23 views
2

我對asp.net mvc3應用程序的UnitTests有點問題。爲什麼單元測試使用mstest命令行失敗,但不在VS2010 Professional中?

如果我在Visual Studio 2010 專業版中運行一些單元測試,它們已成功通過。

如果我使用Visual Studio 2010專業版命令行

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. 

我的控制器

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旗艦版/高級版可能會解決。

回答

0

我發現了這個問題。問題是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); 
} 

什麼是需要的作品:

詞根記憶控制器構造與像

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

2的參數。在測試或單位噸EST類,創建一個模擬像

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電流測試方法IndexTest

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

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

現在的單元測試將作品。不適用於集成測試。在那裏你必須提供連接到數據庫的配置,並且不應用模擬,只需使用我的問題中的代碼即可。

經過5-6個小時的研究,希望得到這個幫助:)

相關問題