In writing PHPSPEC tests for a Zend Framework 2 application, I'm left wondering how far to 'dig'. Consider this very simple case:

A DomainService (Domain in the URL sense of the word) should be able to list all Foo objects, works.

Making heads/tails of the test is not simple. This DomainService is fed via DI with a DomainMapper. This DomainMapper is a Doctrine Mapper that transforms MySQL rows into Doctrine Entities. In theory, would I not want to cover that my code can:

  1. instantiate the DomainService (but this is done through ZF2 Factories -- I'm completely bypassing the Factory process in using phpspec's let). Does this tailspin into a separate test for the Factory, that needs a functional service locator object?
  2. test that it can find all Foo objects, but this means invoking Doctrine and running an SQL query. The test shouldn't be database dependent I assume, we wouldn't want external data to modify the test. But what then should I test, that it successfully returns an empty array? Semantic query errors could create empty array conditions that are failures. Do we simply accept that tests don't cover this?

Where do you draw the line? Testing DI'ed services that interact with databases can't automatically be off-limits?


One of the primary strengths of DI is that you can inject completely different versions of the dependent services based on your environment.
More specifically, in your unit test environment, you can inject a DomainMapper implementation that just returns canned data and does not access the database in any way. You can even vary the DomainMapper instance for every test case, so that in one test the mapper returns an error, in a second test it returns an empty list and in a third it returns a very large list.

What you want to cover in the unit tests of DomainService is

  • that the DomainService fulfils its requirements, if the DomainMapper returns lists of Foo objects with various lengths.
  • that the DomainService does not break completely, if the DomainMapper reports an error, or fulfils the requirements for handling such errors.

Being able to instantiate a DomainService object is usually not a separate test goal, but it is implicitly tested with the other tests.
Being able to obtain an instance through a ZF2 Factory would be a test for that factory or possibly an integration test.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.