Skip to content

Instantly share code, notes, and snippets.

@EricRohlfs
Created May 7, 2015 20:42
Show Gist options
  • Save EricRohlfs/64bb6374e52fbdcc3047 to your computer and use it in GitHub Desktop.
Save EricRohlfs/64bb6374e52fbdcc3047 to your computer and use it in GitHub Desktop.
Unit Testing Invalid Model State in WebApi2
[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();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment