Asp.net-Mvc
測試使用 User.Identity.Name 的控制器操作
我有一個依賴 User.Identity.Name 來獲取目前使用者的使用者名以獲取他的訂單列表的操作:
public ActionResult XLineas() { ViewData["Filtre"] = _options.Filtre; ViewData["NomesPendents"] = _options.NomesPendents; return View(_repository.ObteLiniesPedido(User.Identity.Name,_options.Filtre,_options.NomesPendents)); }現在我正在嘗試為此編寫單元測試,但我陷入瞭如何為 User.Identity.Name 提供 Mock 的問題上。如果我按我的方式執行測試(沒有使用者的模擬…),我會得到一個 Null.. 異常。
哪個是正確的方法?我認為我的操作程式碼不適合單元測試。
一個更好的方法是將一個
string參數userName(或一個IPrincipal參數user,如果您需要比名稱更多的資訊)傳遞給 ActionMethod,您可以使用 ActionFilterAttribute 在正常請求中“注入”它。當你測試它時,你只需要提供你自己的模擬對象,因為動作過濾器的程式碼不會執行(在大多數情況下——如果你特別想要的話,有辦法……)Kazi Manzur Rashid 在一篇出色的部落格文章中的第 7 點下詳細描述了這一點。
您可以使用此程式碼
public SomeController CreateControllerForUser(string userName) { var mock = new Mock<ControllerContext>(); mock.SetupGet(p => p.HttpContext.User.Identity.Name).Returns(userName); mock.SetupGet(p => p.HttpContext.Request.IsAuthenticated).Returns(true); var controller = new SomeController(); controller.ControllerContext = mock.Object; return controller; }它使用Moq模擬框架,但確保你可以使用任何你喜歡的東西。