3

asp.netmvc3アプリケーションのUnitTestsに少し問題があります。

Visual Studio 2010 Professionalでいくつかの単体テストを実行すると、それらは正常に合格しています。

Visual Studio2010Professionalコマンドラインを使用する場合

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:VS2010のMSTestでテスト実行エラーを読みましたが、VS2010 Ultimate/Premiumを使用している場合は解決できます。

4

1 に答える 1

1

問題を見つけました。問題は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.テストまたはユニットテストクラスで、次のようなモックを作成します

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"]);
}

これで、単体テストが機能します。統合テストには適用されません。そこで、DBへの接続の構成を提供する必要があり、モックを適用せずに、私の質問のコードを使用してください。

5〜6時間調査した後、この助けを願っています:)

于 2012-10-12T18:34:58.833 に答える