简体   繁体   English

单元测试asp.net路由映射扩展方法

[英]Unit test asp.net route mapping extension method

I have an extension class for Routes. 我有一个Routes的扩展类。 I want to test the updated list of routecollection. 我想测试更新的routecollection列表。 This is an extract: 这是一个摘录:

public static void MapMyRoutes(this RouteCollection routes)
{
    //do some stuff
    routes.MapHttpRoute(null, controllerPath.Path, new { @namespace = controllerPath.Namespace, controller = controllerPath.ControllerName, id = UrlParameter.Optional });
}

I want to unit test this extension, but can't work out how to extract the mapped url from the routecollection: 我想对此扩展进行单元测试,但无法解决如何从routecollection中提取映射的url:

This is a test: 这是一个测验:

[TestMethod]
public void TestMapMyRoutesMapsCorrectly()
{
    var routes = new RouteCollection();
    routes.MapMyRoutes();

    foreach (var route in routes)
    {
        Assert.AreEqual(route.??, "v1/api/myRoute");
    }
}

RoutesCollection is defined as a Collection<RouteBase> so cast each item as a Route, ie: RoutesCollection被定义为Collection<RouteBase>因此将每个项目转换为Route,即:

foreach (var route in routes.Cast<Route>())
{
    // Url may not in fact be the correct property …
    Assert.AreEqual(route.Url, "v1/api/myRoute");
}

To be honest you are putting wrong logic to test void method. 说实话,你正在用错误的逻辑来测试void方法。 As your method is void you should use mock framework and pass the mocked RouteCollection object in MapMyRoutes(this RouteCollection routes) method and then verify routes.MapHttpRoute method call. 由于您的方法是无效的,您应该使用模拟框架并在MapMyRoutes(this RouteCollection routes)方法中传递模拟的RouteCollection对象,然后验证routes.MapHttpRoute方法调用。

Refer this link for code implementation 请参阅此链接以获取代码实现

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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