asp.net mvc testing: can’t get access to object inside action – Education Career Blog

having

public ActionResult Create(CategoryViewModel viewModel)
    {
        if (!ModelState.IsValid)
        {
            return View(viewModel);
        }
        Category category = new Category();
        category.Parent = daoTemplate.FindByID<Category>(viewModel.ParentId);
        category.CopyFrom(viewModel);
        daoTemplate.Save(category);
        return RedirectToAction("Index");
    }

I need to ensure that newly created category has correct parent set. How can I do this, if I have no access to the category object outside of the method?

,

Ultimately, the test you’re proposing is really verifying two things:

1) daoTemplate.FindByID<T>() works as expected

2) The Create method calls daoTemplate.FindByID<T>()

Those should be two separate tests.

The first test should be part of a DaoTemplate fixture – apart from that it’s difficult to comment on it without seeing more of the source code.

Second, to verify that the action calls the expected method, you’ll need to hand-roll a mock object or use a mocking framework. There are numerous popular mocking frameworks for C# (Moq, RhinoMocks, even the venerable NMock2 – see the age-old stackoverflow question What C# mocking framework to use? for a start), and the classic place to get started mocking is Martin Fowler’s article “Mocks aren’t Stubs.”

Leave a Comment