简体   繁体   中英

Is it possible to look up all name alias of a given type (e.g. “int” versus “Int32”)?

I've been writing unit tests to verify the validity of MVC routes. For example,

[Route("foo/bar/{id:int}")]
public IHttpActionResult SomeAction(int id)
{
   // ... 
}

would be valid but

[Route("foo/bar/{id:List<string>}")]
public IHttpActionResult SomeAction(int id)
{
   // ... 
}

or

[Route("foo/bar/{buzz:int}")]
public IHttpActionResult SomeAction(int id)
{
   // ... 
}

wouldn't.

But the problem is that I'm getting false negatives because, in the first example above, when I check that {int:id} in the route matches a parameter in the action method, the name of the type in the parameter is Int32 via reflection and I don't know how to make my test know that Int32 is the same as int . Is there a way?

I believe that you are writing those unit tests in order to ensure that the routing you configured is on a suitable method and to make sure that on any signature change your test suit will force you to change the routing constraint too.

Therefore I'm assuming that your first method is actually working, and the only problem you are having is with the if("int" == parameterType.Name) that is written somewhere on your test method.

Since you want your test to know that a "int" and a "Int32" are the same, you will need a list of those alias. It can be found here . This list contains the class name from the .Net Framework as well the C# built-in alias. Just create and populate a dictionary and check based on that. Yes, you will have to manually type those pairs.

Just remember that some of the routing constraints are not simply a datatype (for example max or length), but you can just test them against the correspondent datatype too (on the example, int and string).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM