简体   繁体   中英

c# constructor vs initialize

Doing TDD and want to isolate the method under test: Direct(); However, when the test creates MyClass , SomeClass.SetupStuff(); blows up ( NotImplementedException ). So, modified the IMyClass interface to have a Configure(); method that can be called after MyClass construction to avoid the exception.

Question: Is this an accepted way of handling this scenario or is there some basic OOP principal that this breaks?

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

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.

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