Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I pass data to a phpunit test method?

Tags:

php

phpunit

I am writing phpunit test case method which accept a parameter.

My code is as follows

class myTestCase extends PHPUnit_Framework_TestCase
{
    public function testMyCase($date){

        $resultSet=$this->query("select * from testCase where date='$date'");
        $this->assertTrue($resultSet,True);
    }
}

I am trying to run above test case from linux terminal.

phpunit --filter testMyCase myTestCase.php

But do not know how to pass parameter. Please help.

Thank you.

like image 528
Rahul Singh Avatar asked Feb 26 '26 08:02

Rahul Singh


1 Answers

First, you should be using the most current version of PHPUnit (v6.x). The presence of PHPUnit_Framework_TestCase makes it look like you're using an older version. But I digress...

You want a data provider.

class myTestCase extends PHPUnit_Framework_TestCase
{
    /**
    * @dataProvider providerTestMyCase
    **/

    public function testMyCase($date, $expectedRowCount) {

        $sql  = "select * from testCase where date = '$date'";
        $stmt = self::$pdo->prepare($sql);
        $result = $stmt->execute($sql);

        //We expect the query will always work.
        $this->assertTrue($result);

        //We are expecting the rowcount will be consistent with the expected rowcounts.
        $this->assertSame($expectedRowCount,$stmt->rowCount());
    }

    public funtion providerTestMyCase() {
        return [ [ '2017-08-01' , 76 ]
               , [ '2017-08-02' , 63 ]
               , [ '2017-08-03' , 49 ]
               , [ '2017-08-04' , 31 ]
               , [ '2017-08-05' , 95 ]
               ]
    }
}

Read and re-read: Database Testing as well as @dataProvider

like image 137
DrDamnit Avatar answered Feb 27 '26 20:02

DrDamnit