locked
Unit Testing IHttpActionResult Created vs CreatedAtRoute ActionResult with Attribute Based Routing RRS feed

  • Question

  • User-638259267 posted

    I am using Attribute-based routing in ASP.NET Web API application and therefore, when I am using the Post methods for my ASP.NET Web API methods, the CreatedAtRoute ActionResult return type will not work because I do not have any routes defined in my RouteConfig.cs file since I am using Attribute-based routing instead.

    Therefore, in my ASP.NET Web API method, I am using code similar to the following:

    public IHttpActionResult Post([FromBody]string value)
            {
                int id = 1;
                string createdAtUrl = "http://www.google.com";
    
                return Created(createdAtUrl, id);
            }

    However, the difficulty is encountered when I want to write a Unit Test for this method.

     public void Post()
            {
                // Arrange
                ValuesController controller = new ValuesController();
                int id = 1;
                string createdAtUrl = "http://www.google.com";
    
                // Act
                IHttpActionResult actionResult = controller.Post("value");
                var contentResult = actionResult as CreatedNegotiatedContentResult<int>;
    
    
    
                // Assert
                actionResult.Should().BeOfType<CreatedNegotiatedContentResult<int>>();
                
            }

    If I was using CreatedAtRoute instead, my code would be like this instead:

     public void Post()
            {
                // Arrange
                ValuesController controller = new ValuesController();
                int id = 1;
                string createdAtUrl = "http://www.google.com";
    
                // Act
                IHttpActionResult actionResult = controller.Post("value");
                var createdResult = actionResult as CreatedAtRouteNegotiatedContentResult<int>;
    
    
    
                // Assert
                actionResult.Should().BeOfType<CreatedAtRouteNegotiatedContentResult<int>>();
                createdResult.RouteName.Should().BeEquivalentTo("DefaultApi");
                createdResult.RouteValues["id"].Should().Equals(id);
    
            }

    But instead I need to support Attribute-based routing which would not support this type of Unit Testing, so I need a solution to accommodate this scenario.

    Please advise as to how to solve this problem.

    Wednesday, June 15, 2016 9:41 PM

Answers