This is the part 2 of 3 in PHPUnit Beginner.
This is part 2 of PHPUnit Beginner. In this tutorial we will explain when and how to use data provider in our test.
Table Of Content
1. When to use data provider
When we write a function, we want to make sure it passes a series of edge cases. The same applies to tests. Which means we will need to write multiple tests to test the same function using different set of data. For instance, if we want to test our Calculator class using different data. Without data provider, we would have multiple tests as below:
In this case, we can use data provider function in PHPUnit to avoid duplication in our tests.
2. How to use data provider
A data provider method return an array of arrays or an object that implements the Iterator interface. The test method will be called with the contents of the array as its arguments.
Some key points as blow when using data provider:
- Data provider method must be public.
- Data provider return an array of a collection data.
- Test method use annotation(@dataProvider) to declare its data provider method.
Once we know the key points. It is actually quite straightforward to use data provider. First we create a new public method, which returns an array of a collection data as arguments of the test method.Then we add annotation to the test method to tell PHPUnit which method will provide arguments.
3. Add data provider to our first unit test
Let's modify our tests above using data provider.
- line 18: add a data provider method. Take note that a data provider method must be declared as public.
- line 27: use annotation to declare test method's data provider method.
Now run our test again. It should pass. As you can see, we have utilized data provider to avoid code duplication. Instead of writing three test methods for essentially the same method. We now have only one test method.
4. The end
We have completed the second tutorial of PHPUnit Beginner series.
Next tutorial, we are going to teach you how to use doubles in our tests.
Hopefully this simple tutorial helped you with your development.
If you like our post, please follow us on Twitter and help spread the word. We need your support to continue.
If you have questions or find our mistakes in above tutorial, do leave a comment below to let us know.