views:

459

answers:

3

I have developed some classes with similar behavior, they all implement the same interface. I implemented a factory that creates the appropriate object and returns the interface. I am writing a unit test for the factory. All you get back is an interface to the object. What is the best way to test that the factory has worked correctly?

I would like to know the answer in Java, but if there is a solution that crosses languages I would like to know it.

Number 2. in the answer, would be done like the other answer? If so I will mark the other answer accepted as well and reword my question to adress both a factory where an interface is returned and you have no clue what type of concrete class implemented the interface, and the case where you do know what concrete class was used.

+7  A: 

Since I don't know how your factory method looks like, all I can advise right now is to

  1. Check to see the object is the correct concrete implementation you were looking for:

    IMyInterface fromFactory = factory.create(...);  
    Assert.assertTrue(fromFactory instanceof MyInterfaceImpl1);
    
  2. You can check if the factory setup the concrete instances with valid instance variables.

Cem Catikkas
+1  A: 
if (myNewObject instanceof CorrectClass)
{
    /* pass test */
}

update:

Don't know why this got marked down, so I'll expand it a bit...

public void doTest()
{
    MyInterface inst = MyFactory.createAppropriateObject();
    if (! inst instanceof ExpectedConcreteClass)
    {
        /* FAIL */
    }
}
izb
It was marked down 'cause you should use Assertion instead of a test...
Nicolas
A: 

@cem-catikkas I think it would be more correct to compare the getClass().getName() values. In the case that MyInterfaceImpl1 class is subclassed your test could be broken, as the subclass is instanceof MyInterfaceImpl1. I would rewrite as follow:

IMyInterface fromFactory = factory.create(...);  
Assert.assertEquals(fromFactory.getClass().getName(), MyInterfaceImpl1.class.getName());

If you think this could fail in some way (I can't imagine), make the two verifications.

Marcio Aguiar
I agree, but I don't think checking the equality of the class names is redundant. Just checking for classes should be good enough.
Cem Catikkas
Why would you test that a method from Class returns an equal value, instead of just directly comparing the Class objects?
jdmichal