0

I have the following controller method

    public ActionResult Create(Category category)
    {
        //default values
        if (string.IsNullOrEmpty(category.GeoAreaLevelIdentifier))
        {
            category.GeoAreaLevelIdentifier = "OutputArea";
        }                
        category.CreatorIdentifier = EsdContext.User.UniqueIdentifier.ToString();            
        category.Created = DateTime.Now;

        //validation
        RevalidateModel(category);

        new CategoryBroker().Create(category);
        return JsonNow(category);
    }

which fills some default values to the model and THEN validates it. This is because the client code is allowed to submit a model without some of the required fields. The missing fields are filled by the controller (see above).

RevalidateModel method calls TryValidateModel:

    protected void RevalidateModel(object model)
    {
        ModelState.Clear();
        TryValidateModel(model); //called explicitly since model has been updated
        if (!ModelState.IsValid)
        {
            //error message
        }
    }

But when I call Create method from a unit test, it fails because TryValidateModel expects controllerContext:

     Value cannot be null.Parameter name: controllerContext

What is the best way to solve this problem? Should I create the controllerContext eg by MvcContrib TestHelper?

Maxim Eliseev
  • 3,248
  • 4
  • 29
  • 35

1 Answers1

0

In this case

using Moq;
.........
        readonly MockRepository _mockRepository = new MockRepository(MockBehavior.Default);
.........
        controller.ControllerContext = _mockRepository.Create<ControllerContext>().Object;

works good enough.

Best.

Boris
  • 266
  • 2
  • 5
  • It is perfectly ok to mock the ControllerContext - so the test in the question would work without exception. I use it also a lot and wonder why this answer was down voted ... – Alexander Mihailov Nov 20 '18 at 09:35