使用User.Identity.Name测试控制器操作 [英] Testing controller Action that uses User.Identity.Name

查看:117
本文介绍了使用User.Identity.Name测试控制器操作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有依靠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点在<一描述了这一细节href=\"http://weblogs.asp.net/rashid/archive/2009/04/01/asp-net-mvc-best-practices-part-1.aspx\">excellent博客文章。

这篇关于使用User.Identity.Name测试控制器操作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆