加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > asp.Net > 正文

asp.net-mvc – 测试控制器使用User.Identity.Name的操作

发布时间:2020-12-15 19:37:02 所属栏目:asp.Net 来源:网络整理
导读:我有一个操作,依靠User.Identity.Name获取当前用户的用户名,以获得他的订单列表: public ActionResult XLineas() { ViewData["Filtre"] = _options.Filtre; ViewData["NomesPendents"] = _options.NomesPendents; return View(_repository.ObteLiniesPedi
我有一个操作,依靠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));
    }

现在我正试图为这个单元测试,但我困在如何提供一个Mock for User.Identity.Name。如果我运行我的测试,因为我有它(没有嘲笑为User …),我得到一个Null ..异常。

这是正确的方法吗?我认为我的Action代码不适合单元测试。

解决方法

一个更好的方法是传递一个字符串参数userName(或者一个IPrincipal参数用户,如果你需要更多的信息,而不仅仅是名称)到ActionMethod,你在一个正常的请求使用ActionFilterAttribute“注入”。当你测试它,你只是提供自己的模拟对象,因为操作过滤器的代码不会运行(在大多数情况下 – 有办法,如果你特别想要…)

Kazi Manzur Ra??shid在excellent blog post的第7点详细描述了这一点。

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读