PHPUnit – Adding data provider to tests

Instead of hard coding test data in test case, we can specify the data source for a test. In this article we will see how to specify the data provider for a test.

In our previous example, we have seen how to create a test for the function sum of the class Calculator.

In this example, we will add one more function called subtract and it will be tested with PHPUnit using data provider.

1. Add the method subtract to the Calculator class

    class Calculator{
        public function sum($n1, $n2){
            return $n1 + $n2;

        public function subtract($n1, $n2){
            return $n1 - $n2;


2. Add the test method testIsSubtractionCorrect with a data provider

    use PHPUnit\Framework\TestCase;

    class CalculatorTest extends TestCase {

        public function testIsSumCorrect(){
            $calc = new Calculator();
            $result = $calc->sum(1,2.5);
            $expected = 3.5;

            * @dataProvider subtractionProvider
        public function testIsSubtractionCorrect($n1, $n2, $expected){
            $calc = new Calculator();
            $result = $calc->subtract($n1,$n2);            

        public function subtractionProvider(){
            return [
                    "data1"=> [ 1 , 1 , 0],
                    "data2"=> [ -1 , 1 , -2],
                    "data3"=> [ 5 , 1 , 4],
                    "data4"=> [ 1 , 0.25 , 0.75]


3. Running the test

We can run the test by executing the given below command at the root of the project

$./vendor/bin/phpunit --testdox tests/CalculatorTest.php

On executing the test, PHPUnit will display the test result as given below :

Comments on this post

No comments.

Leave a Reply

Your email address will not be published. Required fields are marked *

Trackbacks and Pinbacks on this post

No trackbacks.

TrackBack URL