9

I am running a unit test of my PostMyModel route. However, within PostMyModel() I used the line Validate<MyModel>(model) to revalidate my model after it is changed. I am using a test context, so as not to be dependent on the db for the unit tests. I have posted the test context and post method below:

Test Context

class TestAppContext : APIContextInterface
    {

        public DbSet<MyModel> MyModel { get; set; }

        public TestAppContext()
        {
            this.MyModels = new TestMyModelDbSet();
        }

        public int SaveChanges(){
            return 0;
        }
        public void MarkAsModified(Object item) {

        }

        public void Dispose() { }

    }

Post Method

[Route(""), ResponseType(typeof(MyModel))]
        public IHttpActionResult PostMyModel(MyModel model)
        {
            //Save model in DB
            model.status = "Waiting";
            ModelState.Clear();
            Validate<MyModel>(model);

            if (!ModelState.IsValid)
            {
                return BadRequest(ModelState);
            }

            db.MyModels.Add(model);

            try
            {
                db.SaveChanges();
            }
            catch (DbUpdateException)
            {
                if (MyModelExists(model.id))
                {
                    return Conflict();
                }
                else
                {
                    throw;
                }
            }

            return CreatedAtRoute("DisplayMyModel", new { id = model.id }, model);
        }

When the Validate<MyModel>(model) line runs, I get the error :

System.InvalidOperationException: ApiController.Configuration must not be null.

How can I correct this?

steventnorris
  • 5,656
  • 23
  • 93
  • 174

1 Answers1

23

In order for the Validate command to run, there must be mock HttpRequest associated with the controller. The code to do this is below. This will mock a default HttpRequest, which is fairly unused in this case, allowing the method to be unit tested.

 HttpConfiguration configuration = new HttpConfiguration();
            HttpRequestMessage request = new HttpRequestMessage();
            controller.Request = request;
            controller.Request.Properties["MS_HttpConfiguration"] = configuration;
steventnorris
  • 5,656
  • 23
  • 93
  • 174
  • 4
    Could be simpler with: controller.Request = new HttpRequestMessage(); controller.Request.Properties["MS_HttpConfiguration"] = new HttpConfiguration(); – ccook Jun 22 '16 at 22:38
  • You can set configuration this way too: controller.Request.SetConfiguration(configuration) – Rady Dec 04 '19 at 19:22
  • You can also use the static property `HttpPropertyKeys.HttpConfigurationKey` from the namespace `System.Web.Http.Hosting` for the property key `MS_HttpConfiguration`. – Andriy Tolstoy Oct 05 '21 at 08:21