Simple Membership プロバイダーを使用するコントローラーを単体テストする方法は?
コントローラーは MyViewModel オブジェクトを入力として受け取り、それを DB に挿入します。操作が正常に完了すると、ユーザーはダッシュボードにリダイレクトされます。
コントローラーは依存関係として WebSecurity を持っています。したがって、単体テストを行うと、次の行で HttpContext のパラメーター null 例外が発生します
userLakshya.UserId = WebSecurity.HasUserId ? WebSecurity.CurrentUserId : -1;
HttpContext パラメーターをコントローラーに渡すにはどうすればよいですか?
コード リスト:
[HttpPost]
public ActionResult Create(MyViewModel myVM)
{
MyModel myModel = myVM.Model;
if (ModelState.IsValid)
{
userLakshya.UserId = WebSecurity.HasUserId ? WebSecurity.CurrentUserId : -1;
db.MyModels.Add(myModel);
db.SaveChanges();
return RedirectToAction("Dashboard");
}
return View(myVM);
}
[TestMethod]
public void TestLoginAndRedirectionToDashboard()
{
MyController cntlr = new MyController();
var ret = ulCntlr.Create(new MyViewModel(){
//Initialize few properties to test
});
/*
* Controller throws parameter null exception for HttpContext
* => Issue: Should I pass this? since the controller uses WebSecurity inside
* */
ViewResult vResult = ret as ViewResult;
if (vResult != null)
{
Assert.IsInstanceOfType(vResult.Model, typeof(UserLakshya));
UserLakshya model = vResult.Model as UserLakshya;
if (model != null)
{
//Assert few properties from the return type.
}
}
}