如何在使用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