Small reminder how to fake User.Identity.IsAuthenticated and User.Identity.Name inside unit tests, while testing controller code. It’s not so obvious and I often forget this small trick, which is also important when writing user authentication code (login).

In unit test we want to validate model properties, specially CanWriteStory which has to be True if user is authenticated.

Simple unit test for this controller:

This test will pass (User.Identity.IsAuthenticated will be True) because we configured authentication type “someAuthTypeName” (here and here)! Without looking at MVC source code it would take me a long time to figure that out, and to be honest correlation between IsAuthenticated and AuthenticationType is still little bit confusing.

The test also shows how simple it is to set HttpContext to controller, without need of using some mocking framework. If I’m brave enough, I would try to write similar test for WebForms and Page class, but I’m not

Same rule, with setting of authentication type applies when writing custom login code, which looks probably something like this: