我正在尝试在 MVC 中进行一些单元测试,但是我的一些功能需要 UserID 才能工作(即作为外键保存到数据库中)。
UserID 存储在UserData
我将如何在单元测试时“伪造”UserID 的属性中,FormsAuthenticationTicket
以便我可以使用假用户运行单元测试。这甚至可能吗?
我正在使用 Microsoft 的内置单元测试系统。
我计划使用的测试代码类似于
[TestMethod]
public void EnsureAddItemAddsItems()
{
// Arrange
ShoppingCartController controller = new ShoppingCartController();
// These would be populated by dummy values
Guid itemID = Guid.Empty;
Guid itemTypeID = Guid.Empty;
// Act
ViewResult result = controller.AddItem(itemTypeID, itemID);
//Assert
Assert.AreEqual("Your shopping cart contains 1 item(s)",result.ViewBag.Message);
}
一些示例代码可能如下所示:-
public ActionResult AddItem(Guid itemType, Guid itemID, string returnAction)
{
ShoppingCartViewModel oModel = new ShoppingCartViewModel();
string szName = String.Empty;
int price = 0;
using (var context = new entityModel())
{
// This is the section I'm worries about
>>>>>>>>> Guid gUserID = this.GetCurrentUserID(); <<<<<<<<<
var currentSession = this.CreateOrContinueCurrentCartSession(gUserID);
var oItem = new ShoppingCartItem();
oItem.Id = Guid.NewGuid();
oItem.ItemId = itemID;
oItem.ItemTypeId = itemType;
oItem.ItemName = szName;
oItem.ShoppingCartSessionId = currentSession.ID;
oItem.Price = 1;
context.ShoppingCartItems.AddObject(oItem);
context.SaveChanges();
}
this.FlashInfo("Item added to shopping cart");
ViewBag.Message(string.Format("Your shopping cart contains {0} item(s)",AnotherFunctionThatJustCountsTheValues()));
return this.View();
}
突出显示的行是我获取用户 ID 的地方,该函数只是一个扩展函数,它不做任何复杂的事情,它只是获取保存为FormsAuthenticationTicket.UserData
字段的用户 ID。