theShadow89
theShadow89

Reputation: 1549

TDD and Factory Pattern

I am new to TDD. I try to implement an application that reads a configuration from a file and do some things.

I have a conf element interface:

interface ConfElement{
    doSomething()
}

then I have a two ConcreteConfElement that implements ConfElement:

ConcreteConfElementA:

class ConcreteConfElementA implements ConfElement{
     private propA;

     doSomething()
}

ConcreteConfElementB:

class ConcreteConfElementB implements ConfElement{

     private propB;

     doSomething()
}

then I have a factory that create ConcreteConfElementA and ConcreteConfElementB read from Configuration object passed to factory;

ConfElementFactory(){
  public ConfElementFactory(Configuration conf)

  ConfElement createConf(){
     if(conf.hasElA){
         return new ConcreteConfElementA();
     }
     else{
         return new ConcreteConfElementB();
     }
  }
}

How can I test factory method ? Is it well designed for TDD?

Upvotes: 2

Views: 1114

Answers (2)

MikeJ
MikeJ

Reputation: 2437

With TDD you need to write the tests first, before the production code. TDD encourages design patterns to emerge overtime, rather than straight away.

  • Write a test for use case 1
  • Implement enough code to pass this test (no interfaces!)
  • Test Passes
  • Write a test for use case 2
  • Implement enough code to pass this test
  • Test Passes
  • Refactor to remove duplicate (hint: The Factory pattern emerges!)

This way the code is 100% tested and no need to worry of the pattern is testable or not. Refactoring is a key element of TDD.

Upvotes: 2

dm03514
dm03514

Reputation: 55962

It should be relatively easy to test the conditional logic of your factory. Two tests could be:

  1. Instantiate a Configuration object with hasEla to be true. Instantiate Element factory with the test Configuration object and assert that an instance of ConcreteConfElementA has been returned.

  2. Repeat step one but set hasEla to false, and assert that ElementB has been returned.


I believe this particular factory is testable, because it allows the caller to inject the Configuration.

Upvotes: 1

Related Questions