dxw/iguana

Add a factory to make testing easier

Closed this issue · 2 comments

How can we mock an object if it's instantiated directly in a class? In one recent project I made a Factory class and had started doing $this->factory->getNewInstance(\Dxw\...); in order to make it easier to test.

Do we need one of those?

The solution is usually to inject an instance rather than initialising it in the class. You can then inject a mock in tests.

The 'item factory' pattern doesn't really help here: you'd have to inject the factory in order to mock it in tests. If you're happy injecting a factory, then injecting the object itself instead is more straightforward.

The factory pattern which is sometimes used instead of dependency injection is the 'factory method' pattern: e.g. if you have a dependent mailer object then define a getMailer() method which adds the class after initialise time.

However, I think this is considered an antipattern and DI is better.

I'm not sure what I was referring to in this issue.