How to test an MVC route with optional querystring parameters
-
11-06-2021 - |
Вопрос
I have this controller method:
[GET("/whatever/list")]
public ActionResult Index(string sortby, string order)
I'm trying to test it with MvcContrib route testing:
"~/whatever/list".ShouldMapTo<MyController>(c => c.Index(string.Empty, string.Empty));
"~/whatever/list?sortby=type&order=desc".ShouldMapTo<MyController>(c => c.Index("type", "desc"));
However, it returns this error.
Failure: MvcContrib.TestHelper.AssertionException : Value for parameter 'sortby' did not match: expected '' but was ''; no value found in the route context action parameter named 'sortby' - does your matching route contain a token called 'sortby'?
What am I missing?
Решение
Based on the assert message (expected '' but was '';
so one of the values is null
or string.Empty
in the assertation) your first test is failing, because you used string.Empty
but the default value for string is null
Change your assert to use null
and it should wotk:
"~/whatever/list".ShouldMapTo<MyController>(c => c.Index(null, null));
Другие советы
I used like
var route = "~/whatever/list".WithMethod(HttpVerbs.Get);
route.Values.Add("sortby", "type");
route.Values.Add("order", "desc");
route.ShouldMapTo<MyController>(c => c.Index("type", "desc"));
Не связан с StackOverflow