3

So far I tried searching for an answer, what I found was something query string related, custom model binders or something with the viewbag (irrelevant). Being still pretty new to C# and not very familiar with its internal workings such as this, so I don't feel I can make sense of the answers or translate them into this situation. (Like this) With this question I'm hoping to find an answer with comment or a few of explanation.

The situation:

I want to test if the model binding attributes are configured correctly. Main motivation is TDD, a specific configuration is required and needs to be test driven. Another motivation is that if someone messes with it and breaks it, the test will immediately tell where the problem is.

Example Controller with a single endpoint (the route has to be that way):

    [ApiController]
    [Route("/cats")]
    public class CatsController : ControllerBase
    {
        [HttpGet]
        [Route("cat-breed/{cat_breed}/cat-size/{cat_size}")]
        public IActionResult GetMultipleCats([FromRoute] GetCatsRequestObject request)
        {
            //implementation is not important

            return Ok();
        }
    }

A request object to encapsulate input fields (one of our standards):

    public class GetCatsRequestObject
    {
        [FromRoute(Name = "cat_breed")]   public string CatBreed { get; set; }
        [FromRoute(Name = "cat_size")]    public string CatSize { get; set; }
    }

What I'm looking for is the test, where I somehow do a call with the url to whatever is doing model binding, and then in the controller I check if the values from the url are in the correct places in/and in my request object. Something like this:

private CatsController _controllerUnderTest = new CatsController();

[Test]
public void GivenSomeUrl_WhenControllerIsCalledWithIt_ThenParametersFromUrlGetBindedCorrectly()
{
    //arrange
    string urlpart = "/cats/cat-breed/British%20Shorthair/cat-size/Medium%20Large";
    GetCatsRequestObject expectedResult = new GetCatsRequestObject() { CatBreed = "British Shorthair", CatSize = "Medium Large" };

    // The rest of the setup I don't know how to do

    //act
    // somehow do a call with the url, rather than request object.

    //assert
    // somehow capture the model binding result and compare it with expected result.
}

Is this possible to test? How would you do this? I realize this is a lengthy post, so I thank you for taking your time to read this.

  • Do you want a unit test or integration tests are, too, a valid approach? There is possibility that it could be possible to test only if the whole pipeline of ASP.Net MVC is running. – cassandrad Apr 24 '20 at 14:21
  • Ideally it would be a unit test, but not being sure it's possible I'd say an Integration test is fine as well, so long this gets tested in the end. – Liudvikas Taluntis Apr 26 '20 at 11:01

0 Answers0