0

I have this method that I would like to unit test. Since it's creating the Sql object inside the method, I can't mock it.

Initially I thought about making Sql be an instance property except that I'd have to reset it every time I use it in other methods and this will most likely lead to hard to debug errors (I don't want the possibility to get a "dirty" Sql object on other subsequent calls to its getter if at all avoidable).

What's the common pattern for testing these kinds of methods?

public function getConfigFromDb()
{
    if (!is_null($this->configInDb)) {
        return $this->configInDb;
    }

    $sql = new Sql($this->getSlaveDbAdapter());

    $select = $sql->select()
                  ->from('mytable');

    $statement = $sql->prepareStatementForSqlObject($select);
    $results   = $statement->execute();
    $results->buffer();

    $this->configInDb = $return;

    return $results;
}
2
  • In your case, I would add a SqlFactory and register it as a service (in factories param in service manager config), that way you can easily mock the service and the objects you'll get from it. Commented Dec 12, 2013 at 8:49
  • @SmasherHell why did you post this as a comment instead of an answer? This looks perfectly reasonable. Commented Dec 12, 2013 at 18:50

1 Answer 1

1

@Julian you're right, I'll put it as an answer

In this case, I would add a SqlFactory and register it as a service (in factories param in service manager config), that way you can easily mock the service and the objects you'll get from it.

To go further on the subject, I delegate all object creation to factories that I can call using ServiceManager. The fact is, that way, I can test my Factory in isolation, injecting all dependencies it needs, asserting that the actual object created is the expected object. And anytime I need an object from Factory in the method tested, I can serve a real instance, or a Mock.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.