简体   繁体   English

C#构造函数与初始化

[英]c# constructor vs initialize

Doing TDD and want to isolate the method under test: Direct(); 做TDD并想隔离被测方法: Direct(); However, when the test creates MyClass , SomeClass.SetupStuff(); 但是,当测试创建MyClassSomeClass.SetupStuff(); blows up ( NotImplementedException ). 炸毁( NotImplementedException )。 So, modified the IMyClass interface to have a Configure(); 因此,修改了IMyClass接口以使其具有Configure(); IMyClass method that can be called after MyClass construction to avoid the exception. 可以在构造MyClass之后避免发生异常的方法。

Question: Is this an accepted way of handling this scenario or is there some basic OOP principal that this breaks? 问题:这是处理这种情况的一种可接受的方法,还是有一些基本的OOP原则被打破?

public class MyClass : IMyClass
{
  public MyClass()
  {
     // class with static method that sets stuff up
     SomeClass.SetupStuff();
  }
  public void IMyClass.Direct()
  {
     // want to test this
  }
}

vs VS

public class MyClass : IMyClass
{
  public MyClass()
  {

  }
  public void IMyClass.Direct()
  {
     // want to test this
  }
  //
  public void IMyClass.Configure()
  {
    // class with static method that sets stuff up
    SomeClass.SetupStuff();
  }
}

One way to avoid such problems is to use dependency injection 避免此类问题的一种方法是使用依赖注入

public class MyClass : IMyClass
{
    public MyClass(ISomeClass someClass)
    {
        someClass.SetupStuff();
    }

    public void IMyClass.Direct()
    {
       // want to test this
    }
}

By decoupling your class from SomeClass, you are free to provide a mock implementation of ISomeClass during test and can provide a full implementation at runtime. 通过将类与SomeClass分离,您可以在测试过程中自由提供ISomeClass的模拟实现,并且可以在运行时提供完整的实现。

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

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