Lesson 62 of 93 · 6 min read · Updated
Testing TempData and ClaimsPrincipal in ASP.NET Core Controller Unit Tests
On this page
Controllers often read context that the framework normally provides: TempData for one-time messages and User for the signed-in person. In a unit test the framework does not run, so that context is missing. This lesson builds a small TestContextFactory that supplies just enough TempData and ClaimsPrincipal for each scenario, and it covers two traps that make these tests fail for confusing reasons.
Technical Requirements
- .NET 11 SDK
- xUnit 2.9.3
- Moq 4.21.0
- FluentAssertions 7.2.2
- A test project with a
FrameworkReferencetoMicrosoft.AspNetCore.App(forDefaultHttpContext,TempDataDictionaryandClaimsPrincipal)
A Factory for Test Context
The factory has three methods: one for TempData, one for a signed-in user and one for an anonymous user.
M07.WebApp.Tests/TestContextFactory.cs
TempData: Avoid the NullReferenceException
In a running app, TempData is created by ITempDataDictionaryFactory, which comes from dependency injection. A controller made with new has no HttpContext and no services, so its TempData property is null. The first line that writes TempData["Success"] = ... throws a NullReferenceException.
Common mistake: seeing that exception and assuming the action has a bug. The action is fine; the test is missing context. The fix is to assign a real dictionary before calling the action:
M07.WebApp.Tests/MvcControllerTests.cs
TempDataDictionary is the real implementation from ASP.NET Core. It needs a provider that loads and saves values, normally from a cookie or session. NullTempDataProvider loads an empty dictionary and saves nothing. That is all a unit test needs, because the test reads the value straight from the dictionary after the action runs:
M07.WebApp.Tests/ModelStateTests.cs
The message means "'Keyboard' was added". There is no cookie and no second request. The test only checks that the action put the right message in the right key.
ClaimsPrincipal: Three Authorization Branches
The AdminPanel action makes its own authorization decision. It has three outcomes.
M07.WebApp/Controllers/ProductsController.cs
What is the difference between Challenge and Forbid? Challenge means "I do not know who you are". The authentication handler turns it into a 401 or a redirect to the login page. Forbid means "I know who you are, and you may not do this". That becomes a 403. Mixing them up sends a signed-in user to the login page again and again, so both branches deserve a test.
The controller reads User from HttpContext.User. The test sets it through ControllerContext:
M07.WebApp.Tests/ClaimsPrincipalTests.cs
Each test reads as a sentence: an anonymous user gets a challenge, a sales user is forbidden, an admin sees the panel with their own name.
The authenticationType Trap
Look again at AuthenticatedUser. It passes authenticationType: "TestAuth" to the ClaimsIdentity constructor. The string itself does not matter. What matters is that it is not null or empty.
ClaimsIdentity.IsAuthenticated returns true only when AuthenticationType has a value. If you write new ClaimsIdentity(claims), the identity has a name and roles, but IsAuthenticated is false. The admin test then gets a ChallengeResult instead of a ViewResult, and the failure message gives no hint why. This is a classic trap, so the factory hides it in one place and explains it with a comment.
The anonymous user uses the opposite on purpose: new ClaimsIdentity() with no claims and no authentication type.
Keep the Context Minimal
The factory gives each test only what it needs: a name and some roles. It does not configure cookie authentication, JWT validation or authorization policies. Those belong to the production pipeline. Copying them into a unit test makes the test slow and fragile, and it still would not prove that the real pipeline is configured correctly.
If you need to check that [Authorize(Roles = "Admin")] blocks a request, or that your JWT settings accept a real token, write an integration test with WebApplicationFactory. In a controller unit test, check the decision the controller itself makes.
Summary
- A controller created with
newhas noTempData; assignTestContextFactory.CreateTempData()to avoid aNullReferenceException. - A
TempDataDictionarywith a provider that saves nothing is enough to assert the message an action stores. - Set
UserthroughControllerContextwith aDefaultHttpContext. - Always pass an
authenticationTypetoClaimsIdentity, orIsAuthenticatedstaysfalse. Challenge(401) means "who are you?" andForbid(403) means "not allowed"; test both.- Provide only the claims a scenario needs; test the real authentication stack with integration tests.