Friday, September 23, 2016

Mocking TempData in ASP.NET MVC Unit Tests

If you want to mock TempData in your ASP.NET MVC Unit Tests, you will encounter some difficulties with accomplishing this since TempData is based on the Controller context and therefore cannot be readily mocked.

If you start doing some digging for solutions on how to accomplish this, you will inevitable come across this article:

Of course, this works just fine if you only want to deal with TempData, but what if you find yourself needing to mock other objects that are dependent on the Controller context as well such as Session State?

Well, this is where MvcContrib TestHelper comes to the rescue!

Using just a few lines of code, this NuGet package will help you set up all of your MVC Controller dependencies such as TempData as well as Session State and several others!

Unfortunately, when you attempt to install this NuGet package into your Unit Testing project, you will end up seeing some unwanted dependencies (including an older version of ASP.NET MVC):

Fortunately, another clever developer has updated this library to support ASP.NET MVC 4 and later versions!

The name of this NuGet package is StudioDonder.MvcContrib.Mvc4.TestHelper.  You can download this NuGet package from here:

Even though it was originally built for ASP.NET MVC 4, it works just fine with ASP.NET MVC 5 as well:

After installing this NuGet package, you can use it just as if it was the original MvcContrib.TestHelper NuGet package in your code as follows:

No comments:

Post a Comment