我有依靠User.Identity.Name获取当前用户的用户名,以他的指令列表的动作:
I have an action that relies on User.Identity.Name to get the username of the current user to get a list of his orders:
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提供了一个模拟。如果我跑我的测试,因为我把它(无模拟用户...),我得到一个空..例外。
Now I'm trying to write unit tests for this, but I get stuck on how to provide a Mock for User.Identity.Name. If I run my test as I have it (without mock for User...), I get a Null.. exception.
这是该正确的做法?我在想,我的行动code是不好的单元测试。
Which is the correct approach for this? I'm thinking that my Action code is not good for unit testing.
推荐答案这样做的更好的方式是通过一个字符串参数的userName (或的IPrincipal 参数用户,如果你需要的不仅仅是名称的详细信息)到ActionMethod,您在使用ActionFilterAttribute一个正常请求注入。当你测试它,你只要提供自己的模仿对象,作为动作过滤器的code将无法运行(在大多数情况下 - 有办法,如果你特别希望......)
A better way of doing this would be to pass a string argument userName (or an IPrincipal argument user, if you need more information than just the name) to the ActionMethod, which you "inject" in a normal request using an ActionFilterAttribute. When you test it, you just supply your own mock object, as the action filter's code will not run (in most cases - there are ways to, if you specifically want to...)
卡子门祖尔·拉希德下7点在excellent博客文章。
更多推荐
使用User.Identity.Name测试控制器操作
发布评论