Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/asp.net-mvc/15.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Asp.net mvc 需要模拟Url.RouteUrl进行单元测试_Asp.net Mvc_Unit Testing - Fatal编程技术网

Asp.net mvc 需要模拟Url.RouteUrl进行单元测试

Asp.net mvc 需要模拟Url.RouteUrl进行单元测试,asp.net-mvc,unit-testing,Asp.net Mvc,Unit Testing,我的控制器/操作中有以下代码行 var defaultRoute = Url.RouteUrl("Default", new { action = "MyAction", controller = "MyController", id = 1 }); 我正在编写一个单元测试,需要模拟这一行,使其返回一些URL。我不明白我该怎么做。谁能帮我写一个测试这行 谢谢我想我找到了一条与您的问题相关的线索: 问题是,不能模拟未实现接口或将各自的方法/属性设置为虚拟的类 您可以始终为不稳定的类创建一个包装器

我的控制器/操作中有以下代码行

var defaultRoute = Url.RouteUrl("Default", new { action = "MyAction", controller = "MyController", id = 1 });
我正在编写一个单元测试,需要模拟这一行,使其返回一些URL。我不明白我该怎么做。谁能帮我写一个测试这行


谢谢

我想我找到了一条与您的问题相关的线索:


问题是,不能模拟未实现接口或将各自的方法/属性设置为虚拟的类

您可以始终为不稳定的类创建一个包装器类,然后模拟:

public interface IUrlRouterWrapper
{
    // Put any methods you want to mock here...
    void RouteUrl(string routeName, RouteValueDictionary routeValues);
}

public class UrlRouterWrapper : IUrlRouterWrapper
{
    // ... and implement them here, calling through to the real, non-testable class.
    public void RouteUrl(string routeName, RouteValueDictionary routeValues)
    {
        Url.RouteUrl(routeName, routeValues);
    }
}
然后在使用RouteUrl的代码中:

public class SomeOtherClass
{
    private readonly IUrlRouterWrapper _urlRouterWrapper;

    public SomeOtherClass(IUrlRouterWrapper urlRouterWrapper)
    {
        _urlRouterWrapper = urlRouterWrapper;
    }

    public void DoThings()
    {
        // ...
        _urlRouterWrapper.WrapUrl("Default", new { action = "MyAction", controller = "MyController", id = 1 });
        // ...
    }
}

现在,您有了一个易于模仿的界面,
iurlrouterrapper
,您可以对其进行全面测试。

需要做哪些工作?我如何让我的单元测试忽略Url.RouteUrl行有什么解决办法?如何使单元测试忽略Url.RouteUrl行