Francesco B. Francesco B. - 1 year ago 184
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:

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
. If for single valued parameters (not arrays) it works, but not working for arrays. If I debug
I see only

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

string Url = string.Format(
_testName[0], _testName[1],
_testNotificationID, _testNotificationIDBis);

IHttpRouteData routeData = GetRouteData(Url);

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

Answer Source

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.

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download