1

I have a basic test case that puts together a Delta object to pass to my controller's 'PATCH' action which I am able to do successfully. My test code is as follows

[TestMethod]
    public async Task Patch_Product()
    {
        // Act
        var delta = new Delta<Product>(typeof(Product));
        delta.TrySetPropertyValue("Name", "PatchedProduct");
        delta.TrySetPropertyValue("Comment", "A test Product that has been patched");

        var result = await productController.Patch(1, delta);

        // Assert
        Assert.IsNotNull(result);
    }

The moment the code hits the first line in the Patch action which is as follows

Validate(patch.GetEntity());

It fails with the following exception: System.InvalidOperationException: ApiController.Configuration must not be null.

I verified that the ApiController.Configuration is in fact null for all of my other tests as well for GET, POST, DELETE etc. However none of these controller action call the 'Validate()' method which is where this exception is thrown. Has anyone encountered this before? Is there a way to get a test against PATCH work by potentially mocking the context?

I tried passing in a blank configuration as well in my test as follows:

productController.Configuration = new HttpConfiguration();

But this does not seem to work either. I get this exception:

System.IO.FileNotFoundException: Could not load file or assembly 'Newtonsoft.Json, Version=6.0.0.0, Culture=neutral, PublicKeyToken=30ad4fe6b2a6aeed' or one of its dependencies. The system cannot find the file specified.

Sudeep Unnikrishnan
  • 441
  • 1
  • 8
  • 19

1 Answers1

1

The following worked for me in an MVC5 WebApi2 project:

//----- Test the patch
XXXController controller = new XXXController();
HttpConfiguration configuration = new HttpConfiguration();
HttpRequestMessage request = new HttpRequestMessage();
controller.Request = request;
controller.Request.Properties["MS_HttpConfiguration"] = configuration;

Delta<Shipment> patch = new Delta<XXEntity>();
patch.TrySetPropertyValue("Id", xx.Id);
patch.TrySetPropertyValue("Notes", "Test Comment");

controller.Patch(xx.Id, patch);

This is based on information from prearrangedchaos in https://aspnetwebstack.codeplex.com/discussions/358709 (which suggests that this is an MVC4 solution and that a better WebApi2 solution might exist).

In looking for my solution I also found a related question that might be useful if you have problems with Url (I didn't): Unit Test with route data not working on ASP.NET MVC 5 Web API

Community
  • 1
  • 1
christutty
  • 952
  • 5
  • 12