Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/asp.net-mvc/15.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Asp.net mvc 测试使用User.Identity.Name的控制器操作_Asp.net Mvc_Unit Testing_Nunit_Moq - Fatal编程技术网

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

Asp.net mvc 测试使用User.Identity.Name的控制器操作,asp.net-mvc,unit-testing,nunit,moq,Asp.net Mvc,Unit Testing,Nunit,Moq,我有一个操作依赖于User.Identity.Name获取当前用户的用户名以获取其订单列表: public ActionResult XLineas() { ViewData["Filtre"] = _options.Filtre; ViewData["NomesPendents"] = _options.NomesPendents; return View(_repository.ObteLiniesPedido(User.Identit

我有一个操作依赖于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。。例外


哪种方法是正确的?我认为我的操作代码不适合进行单元测试。

更好的方法是将
字符串
参数
用户名
(或者
I主参数
参数
用户
,如果您需要更多信息而不仅仅是名称)传递给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;
}
public SomeController CreateControllerForUser(字符串用户名)
{
var mock=new mock();
SetupGet(p=>p.HttpContext.User.Identity.Name).Returns(用户名);
SetupGet(p=>p.HttpContext.Request.IsAuthenticated)。返回(true);
var controller=new SomeController();
controller.ControllerContext=mock.Object;
返回控制器;
}

它使用模拟框架,但您可以使用任何您喜欢的东西

太好了。我必须更多地研究ActionFilters。。。谢谢。我经常在考试时嘲笑我的校长。它允许我测试用户信息(用户名)和授权(user.Identity.IsInRole)。我也可以。另一方面,仅仅为了访问当前用户的用户名而模仿IPrincipal(而不是别的),这有点过头了……)传递IPrincipal或IIdentity对象时,需要使用接口和包装器。仅仅使用ActionFilter会导致一个错误,说您无法实现接口。我更喜欢修改代码,以便在用户未经授权时立即抛出InvalidOperationException。还要注意的是,您可能无论如何都应该为ActionFilterAttribute编写单元测试,并且仍然必须至少模拟这些东西一次。对于像我这样想知道:此代码示例使用的代码。在WebAPI中,我喜欢这样的
MyController controller=new MyController();controller.User=新的GenericPrincipal(新的GenericEntity(用户名,“Passport”)、新的[]{“tester”}@Ravi如何?(尽管这在过去的2.5年里可能已经改变了)@Wolfzoon我必须诚实。我不再使用DotNet了。我不记得回答这个:-)。原谅我。