Thursday, May 7, 2015

Unit Testing Invalid Model State in a WebApi 2 Controller

I choose to do this operation in two different tests.
1. Test the controller behavior when the model state is invalid.  Do this by forcing the model state to invalid by adding an entry before the method is called.
2. Test the model state attributes independently from the controller.

For the controller Test

[TestMethod]
public void WhenModelStateIsInvalidDoNotSave()
{
  var mockRepo = new Mock<IProductRepo>();
  mockRepo.Setup(x=>x.Save(It.IsAny<Product>());

  var ctrl = new ProductController(mockRepo.Object);
  ctrl.ModelState.AddModelError("SomeRandomProperty","SomeRandomProperty was not valid");

  var actual = ctrl.Post(new Product());

  mockRepo.Verify(x=>x.Save(It.IsAny<int>()),Times.Never);
  Assert.IsInstanceOfType(actual, typeof(InvalidModelStateResult));
}


public IHttpActionResult Post([FromBody] Product model)
{
  if(!ModelState.IsValid)
    {
       return BadRequest(ModelState);
     }
   
   ProductRepo.Save(model);
    return Ok();
}

1 comment: