使用User.Identity.Name测试控制器操作

编程入门 行业动态 更新时间:2024-10-23 13:22:57
本文介绍了使用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点在excellent博客文章。

更多推荐

使用User.Identity.Name测试控制器操作

本文发布于:2023-11-17 04:59:46,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1608919.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:控制器   操作   测试   User   Identity

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!