简体   繁体   English

在ASP.NET WebApi控制器中模拟User.Identity

[英]Mocking User.Identity in ASP.NET WebApi Controllers

How can you mock the User.Identity [for unit testing] of the ASP.NET WebApi ApiControllers? 您如何模拟ASP.NET WebApi ApiController的User.Identity(用于单元测试)?

Note: 注意:

Some of the controller methods returns are aync [Task] which run on a different thread 一些控制器方法返回的是aync [Task] ,它们在不同的线程上运行

I had to do something similar for an MVC controller test. 对于MVC控制器测试,我必须做类似的事情。 What I ended up doing was attaching a fake HttpContext to the controller and then attaching a GenericPrincipal to the fake context. 我最终要做的是将伪造的HttpContext附加到控制器,然后将GenericPrincipal附加到伪造的上下文。

var myController = new SomeController();
var context = A.Fake<HttpContextBase>();
ControllerContext context = new ControllerContext( new RequestContext( context, new RouteData() ), myController );
myController.ControllerContext = context;
myController.HttpContext.User = new GenericPrincipal( new GenericIdentity( "bob" ), null );

I'm using FakeItEasy so the syntax for generating the fakes may be different for you. 我使用的是FakeItEasy,因此生成伪造品的语法可能与您不同。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM