Why does this ActionFilterAttribute not import data to the ViewModel?
Posted
by Tomas Lycken
on Stack Overflow
See other posts from Stack Overflow
or by Tomas Lycken
Published on 2010-04-16T15:59:20Z
Indexed on
2010/04/16
16:03 UTC
Read the original article
Hit count: 228
I have the following attribute
public class ImportStatusAttribute : ActionFilterAttribute
{
public override void OnActionExecuted(ActionExecutedContext filterContext)
{
var model = (IHasStatus)filterContext.Controller.ViewData.Model;
model.Status = (StatusMessageViewModel)filterContext.Controller.TempData["status"];
filterContext.Controller.ViewData.Model = model;
}
}
which I test with the following test method (the first of several I'll write when this one passes...)
[TestMethod]
public void OnActionExecuted_ImportsStatusFromTempDataToModel()
{
// Arrange
Expect(new
{
Status = new StatusMessageViewModel() { Subject = "The test", Predicate = "has been tested" },
Key = "status"
});
var filterContext = new Mock<ActionExecutedContext>();
var model = new Mock<IHasStatus>();
var tempData = new TempDataDictionary();
var viewData = new ViewDataDictionary(model.Object);
var controller = new FakeController() { ViewData = viewData, TempData = tempData };
tempData.Add(expected.Key, expected.Status);
filterContext.Setup(c => c.Controller).Returns(controller);
var attribute = new ImportStatusAttribute();
// Act
attribute.OnActionExecuted(filterContext.Object);
// Assert
Assert.IsNotNull(model.Object.Status, "The status was not exported");
Assert.AreEqual(model.Object.Status.ToString(), ((StatusMessageViewModel)expected.Status).ToString(), "The status was not the expected");
}
(Expect()
is a method that saves some expectations in the expected
object...)
When I run the test, it fails on the first assertion, and I can't get my head around why. Debugging, I can see that model
is populated correctly, and that (StatusMessageViewModel)filterContext.Controller.TempData["status"]
has the correct data. But after
model.Status = (StatusMessageViewModel)filterContext.Controller.TempData["status"];
model.Status
is still null in my watch window. Why can't I do this?
© Stack Overflow or respective owner