Moq OData Delta Objects To Test Patch Methods

moq logo


Following on from my afternoon with Moq I stumbled upon another fun issue. How the hell could I test my API’s PATCH methods? They all make use of OData’s Delta objects.

public async Task<IActionResult> Patch([FromRoute] Guid id, Delta<ViewModels.SomeThing> something)


It’s actually fairly simple. You just need to create a new Delta object with the correct types then set the delta property value. My “expectedVM” is an autofixture-d object acting as my viewmodel as part of the request body on the PATCH. For extra bonus points you’d replace the “Blah” with an AutoFixture string create as we don’t really care about the value and as good developers we hate magic strings right? 🙂

     var delta = new Delta<ViewModels.Something>(expectedVM.GetType());

            delta.TrySetPropertyValue(nameof(expectedVM.Name), "Blah");
      var result = await myController.Patch(Id, delta);

            var actualModel = ((ObjectResult)result).Value as ViewModels.Something;

            Assert.AreEqual(typeof(OkObjectResult), result.GetType());

            Assert.AreEqual("Blah", actualModel.Name);

Leave a Reply

%d bloggers like this: