【发布时间】:2014-05-21 04:51:11
【问题描述】:
下面是控制器方法(c#)的一段代码:-
public ActionResult SelectProduct(string ProdName, int Block, int ProductAddressId = 0)
{
if (ProductAddressId == 0 && Block == 1 && System.Web.HttpContext.Current.Session["ReturnProductAddressID"] != null)
{
ProductAddressId = (int)System.Web.HttpContext.Current.Session["ReturnProductAddressID"];
}
//other stuffs………
}
以下是单元测试方法:-
[TestMethod]
public void SelectProduct_Condition1_Test()
{
//Arrange
var controller = new ProductController();
var prodName = string.Empty;
var block = 1;
var productAddressId = 0;
//section 1
/*var mockControllerContext = new Mock<ControllerContext>();
var mockSession = new Mock<HttpSessionStateBase>();
mockSession.SetupGet(s => s["ReturnProductAddressID"]).Returns("1");
mockControllerContext.Setup(p => p.HttpContext.Session).Returns(mockSession.Object);*/
//section 2
/*int sessionValue = 1;
var mockControllerContext = new Mock<ControllerContext>();
var mockSession = new Mock<HttpSessionStateBase>();
mockSession.SetupSet(s => s["ReturnProductAddressID"] = It.IsAny<int>()).Callback((string name, object val) => sessionValue = (int)val);
mockSession.SetupGet(s => s["ReturnProductAddressID"]).Returns(() => sessionValue);
mockControllerContext.Setup(p => p.HttpContext.Session).Returns(mockSession.Object);*/
//Act
var actual = controller.SelectProduct(prodName,block,productAddressId);
}
我想问我如何在我的操作方法上测试或模拟会话值(在 if 条件下)?
我在第 1 节和第 2 节中尝试了某些东西(上面单元测试方法中的注释部分)。但没有任何效果。
那么谁能告诉我如何对会话进行单元测试?
编辑:
上面的东西没有工作,而不是下面:-
System.Web.HttpContext.Current.Session["ReturnProductAddressID"] = "12";
表示如果我直接在单元测试方法中设置会话值。但我想知道这是正确的方法吗?
【问题讨论】:
-
你必须使用模拟。快速参考weblogs.asp.net/bleroy/archive/2009/06/15/…
标签: c# asp.net-mvc unit-testing moq