Lesson 62 of 93 · 6 min read · Updated

Testing TempData and ClaimsPrincipal in ASP.NET Core Controller Unit Tests

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

  1. .NET 11 SDK
  2. xUnit 2.9.3
  3. Moq 4.21.0
  4. FluentAssertions 7.2.2
  5. A test project with a FrameworkReference to Microsoft.AspNetCore.App (for DefaultHttpContext, TempDataDictionary and ClaimsPrincipal)

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

/// <summary>
/// The ASP.NET infrastructure does NOT run in a controller unit test. We set up context
/// objects such as TempData and User by hand, ONLY AS FAR AS THE SCENARIO NEEDS.
///
/// GOLDEN RULE: do not copy the whole production authentication stack into a unit
/// test. Provide only the claims you need.
/// If you really want to test the full stack, that is an INTEGRATION test.
/// </summary>
public static class TestContextFactory
{
/// <summary>Creates an in-memory TempData dictionary.</summary>
public static ITempDataDictionary CreateTempData() =>
new TempDataDictionary(new DefaultHttpContext(), new NullTempDataProvider());

/// <summary>Creates an authenticated user with the given name and roles.</summary>
public static ClaimsPrincipal AuthenticatedUser(string name, params string[] roles)
{
var claims = new List<Claim> { new(ClaimTypes.Name, name) };
claims.AddRange(roles.Select(role => new Claim(ClaimTypes.Role, role)));

// Passing the authenticationType parameter is MANDATORY;
// otherwise IsAuthenticated returns false. A classic trap.
return new ClaimsPrincipal(new ClaimsIdentity(claims, authenticationType: "TestAuth"));
}

/// <summary>An unauthenticated (anonymous) user.</summary>
public static ClaimsPrincipal AnonymousUser() => new(new ClaimsIdentity());

private sealed class NullTempDataProvider : ITempDataProvider
{
public IDictionary<string, object?> LoadTempData(HttpContext context) =>
new Dictionary<string, object?>();

public void SaveTempData(HttpContext context, IDictionary<string, object?> values) { }
}
}

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

var sut = new ProductsController(repository.Object)
{
TempData = TestContextFactory.CreateTempData(),
};

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

// TempData is also a PROMISE made to the user; it can be tested.
sut.TempData["Success"].Should().Be("'Klavye' eklendi.");

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

/// <summary>
/// A page only administrators can see.
/// Used in the ClaimsPrincipal test.
/// </summary>
[HttpGet]
public IActionResult AdminPanel()
{
if (User.Identity?.IsAuthenticated != true)
{
return Challenge();
}

if (!User.IsInRole("Admin"))
{
return Forbid();
}

return View(model: User.Identity.Name);
}

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

public class ClaimsPrincipalTests
{
private static ProductsController CreateSut(System.Security.Claims.ClaimsPrincipal user) =>
new(Mock.Of<IProductRepository>())
{
// We feed HttpContext.User through the ControllerContext.
ControllerContext = new ControllerContext
{
HttpContext = new DefaultHttpContext { User = user },
},
};

[Fact]
public void AdminPanel_ForAnonymousUser_ReturnsChallenge()
{
var sut = CreateSut(TestContextFactory.AnonymousUser());

sut.AdminPanel().Should().BeOfType<ChallengeResult>();
}

[Fact]
public void AdminPanel_ForAuthenticatedNonAdmin_ReturnsForbid()
{
var sut = CreateSut(TestContextFactory.AuthenticatedUser("ayse", "Sales"));

sut.AdminPanel().Should().BeOfType<ForbidResult>();
}

[Fact]
public void AdminPanel_ForAdmin_ReturnsViewWithUserName()
{
var sut = CreateSut(TestContextFactory.AuthenticatedUser("ali", "Admin"));

sut.AdminPanel().Should().BeOfType<ViewResult>()
.Which.Model.Should().Be("ali");
}
}

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

  1. A controller created with new has no TempData; assign TestContextFactory.CreateTempData() to avoid a NullReferenceException.
  2. A TempDataDictionary with a provider that saves nothing is enough to assert the message an action stores.
  3. Set User through ControllerContext with a DefaultHttpContext.
  4. Always pass an authenticationType to ClaimsIdentity, or IsAuthenticated stays false.
  5. Challenge (401) means "who are you?" and Forbid (403) means "not allowed"; test both.
  6. Provide only the claims a scenario needs; test the real authentication stack with integration tests.