views:

67

answers:

1

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?

A: 

The problem was that Moq didn't treat the Status property correctly. A call to

model.SetupProperty(c => c.Status);

fixed the problem.

Tomas Lycken