我是单元测试的新手,我需要有关此代码的帮助。它正在使用MVC 4.0,但是有一些数据库的调用,如果我需要打开一个连接,我不明白如何开始创建单元测试,我希望你能帮助我。
这是代码:
[HttpPost]
public ActionResult Add(User user, IEnumerable<int> Groups)
{
HttpCookie cookie = Request.Cookies.Get(SecurityManager.COOKIENAME);
if (cookie != null)
{
if (SecurityManager.HasPermission(int.Parse(cookie.Values.Get("Id")),(int)PermissionEnum.AddUser))
{
List<Group> gs = new List<Group>();
if (Groups != null)
{
foreach (int g in Groups)
{
Group gr = GroupManager.getGroup(g);
gs.Add(gr);
}
}
user.Groups = gs;
if (UserManager.addUserEmployee(user))
{
return RedirectToAction("Index");
}
else
{
ViewBag.groups = new MultiSelectList(
GroupManager.getMyGroups(int.Parse(cookie.Values.Get("Id"))),"Id", "Name", Groups);
ModelState.AddModelError("Error", "Error saving the user.");
return View(user);
}
}
else
{
return RedirectToAction("NoPermission", "Home");
}
}
else
{
return RedirectToAction("Logout", "Home");
}
}
我如何测试RedirectToAction
是什么,因为我有多个?
答案 0 :(得分:1)
要测试RedirectToAction结果,只需将结果转换为RedirectToRouteResult,如下所示:
// test case 1:
RedirectToRouteResult result = controller.AddUser(user, groups) as RedirectToRouteResult;
Assert.Equal("NoPermission", result.RouteValues["action"]);
Assert.Equal("Home", result.RouteValues["controller"]);
// test case 2:
RedirectToRouteResult result = controller.AddUser(user, groups) as RedirectToRouteResult;
Assert.Equal("Logout", result.RouteValues["action"]);
Assert.Equal("Home", result.RouteValues["controller"]);