如何对使用 Simple Membership 提供程序的控制器进行单元测试?
控制器将 MyViewModel 对象作为输入并将其插入数据库。当操作成功完成时,用户被重定向到仪表板。
控制器将 WebSecurity 作为依赖项。因此,在进行单元测试时,我在以下行中得到 HttpContext 的参数空异常
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.
}
}
}