Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I test for TempData being set in MVC 2 where there is a redirect?

When trying to test my MVC 2 controllers, I am having a hard time testing the result of TempData when I'm doing a redirect. It works ok if the result of the controller action is a ViewResult, however, in a redirect, it is RedirectToRouteResult.

So my test is something like this:

var controller = new SubscriptionController(this.dataStorageMock.Object)
    {
        ControllerContext = MvcMockHelpers.GetControllerContextMock("POST")
    };

var actionResult = controller.Create(formCollection);
var redirectResult = (RedirectToRouteResult)actionResult;

// TODO: Need to ensure TempData contains a key "info".

One option is to do the following:

Assert.That(controller.TempData.ContainsKey("info"));

If the result had been a ViewResult it could have been tested like this:

var viewResult = (ViewResult)actionResult;
Assert.That(viewResult.TempData.ContainsKey("info"));

Is there a way to test RedirectToRouteResult the same way as the ViewResult can be tested?

Thanks

like image 616
Nathan Avatar asked Oct 29 '10 19:10

Nathan


People also ask

Can TempData persist across action redirects?

TempData is used to pass data from current request to subsequent request (i.e., redirecting from one page to another). Its life is too short and lies only till the target view is fully loaded. But you can persist data in TempData by calling the method Keep () .

Does TempData used to pass data from one page to another page in MVC?

It is used to transfer the data from one controller to another controller or it is also from one action to another action method. It is like one page to other page. TempData is derived from TempDataDictionary class.

How does TempData work in MVC?

What is TempData and How to Use in MVC? TempData is used to transfer data from the view to the controller, the controller to the view, or from an action method to another action method of the same or a different controller. TempData temporarily saves data and deletes it automatically after a value is recovered.

Where is TempData stored in MVC?

By default TempData uses the ASP.NET Session as storage. So it is stored on the server ( InProc is the default).


1 Answers

Assert.That(controller.TempData.ContainsKey("info")); is exactly what you need.

like image 141
Darin Dimitrov Avatar answered Sep 18 '22 20:09

Darin Dimitrov