Unit test failures

I run the unit test of my PostMyModel route. However, in PostMyModel() I used the Validate<MyModel>(model) to re-validate my model after changing it. I use a test context to not be db dependent for unit tests. I placed the test context and submit method below:

Testing 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() { } } 

Shipping 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 line Validate<MyModel>(model) is executed, I get an error message:

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

How can i fix this?

+6
source share
1 answer

To run the Validate command, there must be a mock HttpRequest associated with the controller. The code for this is below. This makes fun of HttpRequest by default, which in this case is not quite used, which allows testing the module.

  HttpConfiguration configuration = new HttpConfiguration(); HttpRequestMessage request = new HttpRequestMessage(); controller.Request = request; controller.Request.Properties["MS_HttpConfiguration"] = configuration; 
+15
source

Source: https://habr.com/ru/post/983066/


All Articles