跳过方法执行到单元测试控制器流程

Skip a method execution to unit test controller flow

public class DemoController : Controller
{


    private readonly ICommonOperationsRepository _commonRepo;

    public DemoController (ICommonOperationsRepository commonRepo)
    {
       _commonRepo = commonRepo;
    }
    public ActionResult Default()
    {
       var model = new DemoModel();
       try
       {
           **ConcreteClass cc = new ConcreteClass(Request.ServerVariables["HTTP_X_REWRITE_URL"].ToString());
            cc.ConcreteClassMethod();**

           model.ListTopListing.AddRange(_commonRepo.GetListings());
        }
        catch (Exception ex)
        {
            ExceptionHandler objErr = new ExceptionHandler(ex, "DemoController .Default()\n Exception : " + ex.Message);
            objErr.LogException();
         }
         return View(model);
     }

}

我正在尝试对我的控制器进行单元测试。 ConcreteClass 构造函数及其方法 ConcreteClassMethod 都对 HttpRequest 变量有一定的依赖性,我无法通过我的单元测试。

我想要一种在调用 DemoController 的默认操作时可以简单地跳过 ConcreteClass 的构造函数和 ConcreteClassMethod 的执行的方法。

您不能创建对象的新实例并停止调用构造函数。您将不得不创建一个空的无参数构造函数。

public class ConcreteClass
{
    private string MyString;

    // Your constructor
    public ConcreteClass(string myString)
    {
        this.MyString = myString;
    }

    // Parameterless constructor
    public ConcreteClass()
    {
        // Do nothing, no code
    }

    // A method that might use MyString
    public void DoSomethingWithMyString()
    {
        var trimmedString = this.MyString.Trim();
    }
}

或者重新考虑您的方法的工作方式,使其不依赖于在构造函数中传入的字符串:

public class ConcreteClass
{        
    // No constructor required anymore

    // Pass the string in to the methods that need the string
    public void DoSomethingWithMyString(string myString)
    {
        var trimmedString = myString.Trim();
    }

    // Pass the string in to the methods that need the string
    public void DoSomethingElseWithMyString(string myString)
    {
        var trimmedString = Int32.Parse(myString);
    }
}

但是,这可能无法解决问题,请记住,您想注入 Request 变量但您无权访问它们,难道您不能只执行以下操作:

public class DemoController : Controller
{
    private string HttpRewriteUrl;

    public DemoController()
    {
        this.HttpRewriteUrl = Request.ServerVariables["HTTP_X_REWRITE_URL"].ToString();
    }

    // Custom constructor for unit testing
    public DemoController(string httpRewriteUrl)
    {
        this.HttpRewriteUrl = httpRewriteUrl;
    }

    public ActionResult Default()
    {
        // Get the value from the object
        ConcreteClass cc = new ConcreteClass(this.HttpRewriteUrl);
        cc.ConcreteClassMethod();
    }
}

现在,在您的单元测试中,您可以使用第二个构造函数并将值传递给:

var controller = new DemoController("your value to pass in here");
controller.Default();