O.O
O.O

Reputation: 11287

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();
  }
}

Upvotes: 2

Views: 177

Answers (1)

David Arno
David Arno

Reputation: 43254

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.

Upvotes: 5

Related Questions