Jonathas Costa
Jonathas Costa

Reputation: 1016

How to test a class that sets up its properties on constructor?

I have a lot of classes implementing some interfaces and I built some classes that "coordinates" the usage. So, I created a base class that contains the orchestration, and built a class for each combination of these interface implementations that I needed. Something like this:

public abstract class BaseDirector
{
   public IInterfaceA A { get; set; }
   public IInterfaceB B { get; set; }

   public virtual void Do()
   {
      A.Do();
      B.Do();
   }
}

public class Director1: BaseDirector
{
   public Director1()
   {
      A = new A1();
      B = new B2();
   }
}

public class Director2: BaseDirector
{
   public Director2()
   {
      A = new A2();
      B = new B12();
   }
}

It smells bad and I don't see how I can test this. Can someone give some directions on how to test this? Do I need to change the approach on "director" classes?

Upvotes: 1

Views: 25

Answers (1)

mawalker
mawalker

Reputation: 2070

You make each implementation have constructors that support dependency injection (passing in values instead of creating them internally) I'm not 100% sure in c#, but I think you can require a constructor like this by creating a similar constructor in the base class. But either way you can just 'manually' make both no-op and D.I. constructor for each impl.

public class Director1: BaseDirector
{
   public Director1()
   {
      A = new A1();
      B = new B2();
   }
   public Director1(A a, B b) // Make a constructor that handles "dependency injection"
   {
      A = a;
      B = b;
   }
}

public class Director2: BaseDirector
{
   public Director2()
   {
      A = new A2();
      B = new B12();
   }
   public Director2(A a, B b) // Make a constructor that handles "dependency injection"
   {
      A = a;
      B = b;
   }
}

This allows you to 'inject' values you want for testing purposes.

Upvotes: 1

Related Questions