AnthonySteele / MvcRouteTester

A library for unit testing ASP MVC route tables for both Web and API Routes
Apache License 2.0
105 stars 43 forks source link

How do you test for optional parameters? #30

Closed danbadge closed 4 years ago

danbadge commented 10 years ago

We've got an optional parameter and we're testing that the route can still be found when the parameter is not passed. Our example controller and test is below, the route works when you make a proper http request but the test fails with the following error: MvcRouteTester.Assertions.AssertionException : Expected '', got missing value for 'shopId' at url '/track/1/format/17/price'.

Here's our controller:

[RoutePrefix("track")]
public class TrackPriceController : ApiController
{
    [Route("{trackId}/format/{formatId}/price")]
    public ErrorResponse Get(int trackId, int formatId, int? shopId = null)
    {
        // something
    }
}

And here's our tests:

    [SetUp]
    public void SetUp()
    {
        _config = new HttpConfiguration();
        _config.MapHttpAttributeRoutes();
        _config.EnsureInitialized();
    }

    // failing test
    [Test]
    public void Should_find_track_route_without_shopId()
    {
        _config.ShouldMap("/track/1/format/17/price")
            .To<TrackPriceController>(HttpMethod.Get, x => x.Get(1, 17, null));
    }

    // passing test
    [Test]
    public void Should_have_track_route()
    {
        _config.ShouldMap("/track/1/format/17/price?shopId=34")
            .To<TrackPriceController>(HttpMethod.Get, x => x.Get(1, 17, 34));
    }
alexjamesbrown commented 10 years ago

I had this earlier, but for a bool value... I worked around it by specifying the value (not what you want to do here)

@AnthonySteele can probably advise if this is supported

AnthonySteele commented 10 years ago

Verified, working on it. https://github.com/AnthonySteele/MvcRouteTester/commit/09c6fc9eee6fef959598a67162ea82573ea6c869

AnthonySteele commented 10 years ago

It may be fixed now. Can you try the latest code? If not, I'll package it to nuget.