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
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 () .
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.
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.
By default TempData uses the ASP.NET Session as storage. So it is stored on the server ( InProc is the default).
Assert.That(controller.TempData.ContainsKey("info"));
is exactly what you need.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With