Francesco B. Francesco B. - 29 days ago 12
ASP.NET (C#) Question

Unit testing Asp.Net WebApi: how to test correct routing of a method with [FromUri] parameters

I'd like to test this controller:

[HttpGet]
public IList<Notification> GetNotificationsByCustomerAndId([FromUri] string[] name, [FromUri] int[] lastNotificationID)
{
return _storage.GetNotifications(name, lastNotificationID, _topX);
}


In particular, in this method I want to test that the array passed in input to form the request Url, is the same array that goes into
routeData.Values
. If for single valued parameters (not arrays) it works, but not working for arrays. If I debug
Values
I see only
controller
and
action
.

[TestMethod]
public void GetNotificationsByCustomerAndId_ArrayOverload_Should_Match_InputParameter_name()
{
string[] _testName = new string[] { _testCustomer, _testCustomerBis };

string Url = string.Format(
"http://www.testpincopallo.it/Notifications/GetByCustomerAndLastID/customersNotificationsInfos?name={0}&name={1}&lastNotificationID={2}&lastNotificationID={3}",
_testName[0], _testName[1],
_testNotificationID, _testNotificationIDBis);

IHttpRouteData routeData = GetRouteData(Url);
routeData.Values["name"].Should().Be(_testName);
}


Is there another way to unit test while you are passing arrays?

Answer

Perhaps you can use List<string> rather than string[] as in this answer?

Also, you might need to put name[] instead of name in the query string.

Edit
After looking into this, I'm wondering whether model binding of non-simple types is not done during the GetRouteData call -- after all, routing does not consider these types and you cannot create two routes that differ by eg. the number of elements in the passed array.

So you should look into model binding instead of request routing. To test your code without actually performing the call, you could retrieve a ModelBinder object manually and use that to parse the URL. This test from the ASP.NET source code might be relevant for you.