Created
May 7, 2015 20:42
-
-
Save EricRohlfs/64bb6374e52fbdcc3047 to your computer and use it in GitHub Desktop.
Unit Testing Invalid Model State in WebApi2
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
[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