Can phpunit use multiple data provider

前端 未结 5 747
渐次进展
渐次进展 2021-02-06 22:50

One question in short: can phpunit use multiple data provider when running test?

For example, I have a method called getById, and I need to run both successful and unsuc

相关标签:
5条回答
  • 2021-02-06 23:14

    Just an update to the question, a pull request was accepted and now the code:

    /** 
     * @dataProvider provideInvalidId
     * @dataProvider provideFailedId
     */
    public function testGetByIdUnsuccess($id)
    {   
        $this->assertNull($this->model->getById($id));
    }
    

    Will work on PHPUnit 5.7, you'll be able to add as many providers as you want.

    0 讨论(0)
  • 2021-02-06 23:15

    You can use a helper function as shown below. The only problem is if the total number of test cases provided by all "sub data providers" is large, it can be tedious to figure out which test case is causing a problem.

    /** 
     * @dataProvider allIds
     */
    public function testGetByIdUnsuccess($id)
    {   
        $this->assertNull($this->model->getById($id));
    }  
    
    public function allIds()
    {
        return array_merge(provideInvalidId(),provideFailedId());
    }
    
    0 讨论(0)
  • 2021-02-06 23:15

    You can add a comment to your dataProvider array, to provide the same functionality, while not requiring multiple dataProviders.

    public static function DataProvider()
    {
        return array(
            'Invalid Id'      => array(123),
            'Failed Id'       => array(321),
            'Id Not Provided' => array(NULL),
    );
    }
    
    0 讨论(0)
  • 2021-02-06 23:18

    You can also use CrossDataProviders which allows you to use a combination of data providers with each other

    <?php
    
    /** 
     * @dataProvider provideInvalidIdAndValues
     */
    public function testGetByIdUnsuccess($id, $value)
    {   
        $this->assertNull($this->model->getById($id));
    }   
    
    function provideInvalidIdAndValues() {
        return DataProviders::cross(
            [[1], [2], [3]],
            [['Rob'], ['John'], ['Dennis']]
        );
    }
    
    0 讨论(0)
  • 2021-02-06 23:30

    well,you could consider it from another side ;) you know exactly what is your expected,for example getById(1) expected result is $result_expected,not $result_null so,you could make a dataprovider like this

    $dataProvider = array(1, 'unexpected');
    

    then,your test method like this:

    public function testGetById($id) {
        $this->assertEquals($result_expected, $obj::getById($id));
    }
    

    so,test result is:

    .F
    
    0 讨论(0)
提交回复
热议问题