Most PHP developers use PHPunit to test their applications.
Although, you might not be familiar with data providers, a cool feature that allows running the same test with different inputs and expected results.
Basically, these functions provide arbitrary arguments you can pass in your tests to improve readability and ease the maintenance.
How to
You'll only need a special attribute and a simple method that returns an array of data.
It's the most basic usage, but the "how" is quite straightforward, so read the documentation (and maybe a few blog posts) and you'll be fine.
4 classic errors with data providers
- Don't use data providers for refactoring. The idea is to test different inputs for different expected results, not to reuse common blocks of code (like with traits or simple private helpers in the same class)
- Be aware data providers run BEFORE the setup, which means you can't access many things within such helpers (so anything initialized in
setUpBeforeClass
orsetUp
won't be accessible) - Don't test the data provider!!! It usually happens when you use some
if/else
conditions in your test just to make it work with your provider. You would introduce unnecessary complexity - Don't forget to typehint the arguments you use in your tests to retrieve data from data providers
3 pro tips for data providers
- You can return iterators and generators by using the
yield
keyword in your provider, which is probably more readable with large arrays of inputs - Data providers are not only meant to return static values. You can return instances and other complex data structures from your provider as well, even closures
- Don't hesitate to define several data providers for different purposes. It's even possible to use multiple providers for the same test
Wrap this up
Data providers can be helpful to run the same test with different inputs and expected results without having to repeat the same lines to define different use cases.
However, it's easy to completely miss the point by introducing unnecessary complexity and complex logic in your providers.
Keep it simple.
Top comments (0)