If you review any Unit Test code samples for ASP.NET Web API, you will find examples on how to Unit Tests when using CreatedAtRoute but they only refer to using the Default Routing rules available in WebApiConfig.cs.
So what do you do if you are using Attribute-based routing?
Well, while this scenario is poorly documented, there is a solution for this as well!
You start by using the Route Name attribute on your Post method as follows:
Now, if you want to Unit Test that code, you can do something like the following:
That is all that is needed in order to support Unit Testing with Attribute-based routing!
So what do you do if you are using Attribute-based routing?
Well, while this scenario is poorly documented, there is a solution for this as well!
You start by using the Route Name attribute on your Post method as follows:
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
[Route("", Name ="MyRoute")] | |
[ResponseType(typeof(Product))] | |
[HttpPost] | |
public IHttpActionResult Post(Product product) | |
{ | |
_repository.Add(product); | |
return CreatedAtRoute("MyRoute", new { id = product.Id }, product); | |
} |
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 PostMethodSetsLocationHeader() | |
{ | |
// Arrange | |
var mockRepository = new Mock<IProductRepository>(); | |
var controller = new Products2Controller(mockRepository.Object); | |
// Act | |
IHttpActionResult actionResult = controller.Post(new Product { Id = 10, Name = "Product1" }); | |
var createdResult = actionResult as CreatedAtRouteNegotiatedContentResult<Product>; | |
// Assert | |
Assert.IsNotNull(createdResult); | |
Assert.AreEqual("MyRoute", createdResult.RouteName); | |
Assert.AreEqual(10, createdResult.RouteValues["id"]); | |
} |
No comments:
Post a Comment