What you need to know about combining @depends and @dataProvider in PHPUnit
Yesterday I was working on some PHPUnit test cases and couldn’t get two of them to work as I wanted them to.
The answer was actually in the documentation and taught me not only about why it wasn’t working but also a lesson about documentation.
What I was trying was to have two texts from which one depended on the other. They were similar to a map/reduce pattern. The fist test was asserting the mapping and the second asserted the reducing.
It made sense to have more than one test data set to map and reduce so I added @dataProvider to the first test.
It then made sense to use the mapped result from the first test as te input to the second so I made my second test @depend on the first.
Nothing worked anymore..
The answer is actually in the documentation at Chapter 4. Writing Tests for PHPUnit / Data Providers:
When a test depends on a test that uses data providers, the depending test will be executed when the test it depends upon is successful for at least one data set. The result of a test that uses data providers cannot be injected into a depending test.
All data providers are executed before the first call to the setUp function. Because of that you can’t access any variables you create there from within a data provider.
So there we go what I wanted it not supposed to work and I have to find another way. Fine.
The lesson I learned about documentation?
Documentation can be redundant. The piece of information above can be read two ways. It is documented at the @dataProvider part which I was looking at first before I decided to use @depends as well. When I looked at the @depends chapter I was already past the @dataProviders chapter and couldn’t find this information.
You see that a piece of information about two things needs to be available for both things. I’m sure that is a bugger to maintain but then documentation isn’t easy.