Validate fails in unit tests

2020-08-22 07:30发布

问题:

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?

回答1:

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;