如何在使用Visual Studio 2012单元测试MVC 4应用程序时使用Microsoft Fakes来模拟User.Identity.Name。 我正在为项目创建操作编写单元测试方法。如何使用Microsoft Fakes来模拟User.Identity.Name
[HttpPost]
public ActionResult Create([Bind(Include = "Name")]Category category)
{
if (categoryService.IsNameExists(category.Name))
{
ModelState.AddModelError("Name", "Category name already exists!");
return View(category);
}
try
{
if (ModelState.IsValid)
{
UserProfile p = new UserProfile();
p.UserName = User.Identity.Name;
category.CreatedBy = p;
category.CreatedDate = DateTime.Now;
category.Active = true;
category.DeletedBy = null;
category = categoryService.SaveCategory(category);
return RedirectToAction("Index");
}
return View(category);
}
catch (DataException dex)
{
}
}
[TestMethod]
public void Create()
{
Category createdCategory = new Category();
ICategoryService service = new StubICategoryService()
{
SaveCategoryCategory = (category) => { return category; }
};
CategoryController controller = new CategoryController(service);
using (ShimsContext.Create())
{
System.Fakes.ShimDateTime.NowGet =() =>
{ return new DateTime(2000, 1, 1); };
ViewResult result = controller.Create(createdCategory) as ViewResult;
Assert.IsNotNull(result);
}
}
这些是我写的操作方法和测试方法。如果还有更好的方法可以做到这一点,请告诉我,(不是另一个嘲讽框架)。
不是直接调用“User.Indenty.Name”,而是使用方法GetCurrentUser创建一个单独的类“CustomUserContext”。这样你可以在测试方法中用你喜欢的任何东西来模拟CustomUserContext。 – artokai