This is part 2 of PHPUnit Beginner. In this tutorial we will explain when and how to use data provider in our test.
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:
<?php
require 'Calculator.php';
class CalculatorTests extends PHPUnit_Framework_TestCase
{
private $calculator;
protected function setUp()
{
$this->calculator = new Calculator();
}
protected function tearDown()
{
$this->calculator = NULL;
}
public function testAdd()
{
$result = $this->calculator->add(1, 2);
$this->assertEquals(3, $result);
}
public function testAddWithZero()
{
$result = $this->calculator->add(0, 0);
$this->assertEquals(0, $result);
}
public function testAddWithNegative()
{
$result = $this->calculator->add(-1, -1);
$this->assertEquals(-2, $result);
}
}
In this case, we can use data provider function in PHPUnit to avoid duplication in our tests.
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:
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.
Let's modify our tests above using data provider.
<?php
require 'Calculator.php';
class CalculatorTests extends PHPUnit_Framework_TestCase
{
private $calculator;
protected function setUp()
{
$this->calculator = new Calculator();
}
protected function tearDown()
{
$this->calculator = NULL;
}
public function addDataProvider() {
return array(
array(1,2,3),
array(0,0,0),
array(-1,-1,-2),
);
}
/**
* @dataProvider addDataProvider
*/
public function testAdd($a, $b, $expected)
{
$result = $this->calculator->add($a, $b);
$this->assertEquals($expected, $result);
}
}
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.
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.