我正在编写单元测试来测试MVC控制器方法(CRUD操作)。控制器方法接受来自会话的usernameIdentity以进行审计。
我正在尝试以下方法来设置ShimHttpSessionStateBase:
[TestMethod()]
public void CategoryCreateTest()
{
using (ShimsContext.Create())
{
var controller = new WebcamsController();
var category = new DataModel.Webcams.Category() { Name = "TestCategory" };
var currentSessionWrapper = new HttpSessionStateWrapper(HttpContext.Current.Session);
var session = new System.Web.Fakes.ShimHttpSessionStateBase(currentSessionWrapper);
session.Instance.Add("usernameIdentity", "DOMAIN\\USERNAME");
controller.ControllerContext = new ControllerContext(controller);
var result = controller.CategoryCreate(category);
Assert.IsInstanceOfType(result, typeof(PartialViewResult));
}
}
我不确定如何正确创建controllerContext,以便在控制器方法中读取Session。
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult CategoryCreate([Bind(Include = "ID,Name")] Category category)
{
try
{
if (category != null
&& Validation.ValidNonNullableString(Session["usernameIdentity"].ToString(), 1, 60) && ModelState.IsValid)
{
businessLayer.SetCategories(category, "Add", AuthenticationHandler.GetHostInternetProtocolAddress, Session["usernameIdentity"].ToString(), AuthenticationHandler.GetUserInternetProtocolAddress);
return PartialView("CategoryList", businessLayer.GetCategoriesByCategory(0, AuthenticationHandler.GetHostInternetProtocolAddress));
}
return jsonResultHandler.JsonResultMessage("Failure", Properties.Resources.GlobalAttributeCreateFailed);
}
catch
{
throw;
}
}