1

How can you mock the User.Identity [for unit testing] of the ASP.NET WebApi ApiControllers?

Note:

Some of the controller methods returns are aync [Task] which run on a different thread

Tawani
  • 11,067
  • 20
  • 82
  • 106
  • This might help: http://stackoverflow.com/questions/162534/mock-iidentity-and-iprincipal – Christian Phillips May 27 '14 at 18:30
  • I would suggest using in-memory http server for integration testing. You can insert delegating handler into the pipeling to handle authentication. This [article](http://www.strathweb.com/2012/06/asp-net-web-api-integration-testing-with-in-memory-hosting/) might help. – Konstantin Smolyakov May 30 '14 at 07:31

1 Answers1

2

I had to do something similar for an MVC controller test. What I ended up doing was attaching a fake HttpContext to the controller and then attaching a GenericPrincipal to the fake context.

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.

Craig W.
  • 17,838
  • 6
  • 49
  • 82
  • 2
    WebApi ApiCOntroller uses HttpControllerContext and does not have an HttpContext property – Tawani Jun 04 '14 at 13:03