TempData is null When Running Unit Tests

When running a unit test (XUnit in my case), my MVC controller threw a NullReferenceException on the TempData object itself:


This is because the TempData object is injected into the Controller by the MVC framework via property injection *after* it is constructed. Since my unit test instantiates it “manually,” I needed to mock that in, too. In my case, using Moq:

var yourController = new YourController(/* your mocked parameters */);
var mockTempData = new Mock<ITempDataDictionary>();
yourController.TempData = mockTempData.Object;
var controllerResult = yourController.YourMethod();

Depending on your controller’s usage of TempData, you might not need to mock in any further behaviors of your mock object!