运行时在phpunit中创建函数

时间:2015-11-17 07:36:28

标签: phpunit

有没有办法通过给出参数来创建测试用例运行时? 测试用例的功能相同,只是名称和参数不同。

就像这里的一个例子

public function testGetGiftsGivenVideo() {
        $fileName = 'get-gifts-given-video.json';
        $filePath = $this->path . $fileName;
        $this->accessToken = $this->coreAPI->GetOAuthToken($this->loginFilePath);
        $this->compareResults($filePath, $this->accessToken, true);
    }

    public function testGetGiftsReceivedAudio() {
        $fileName = 'get-gifts-received-audio.json';
        $filePath = $this->path . $fileName;
        $this->accessToken = $this->coreAPI->GetOAuthToken($this->loginFilePath);
        $this->compareResults($filePath, $this->accessToken, true);
    }

    public function testGetGiftsReceivedVideo() {
        $fileName = 'get-gifts-received-video.json';
        $filePath = $this->path . $fileName;
        $this->accessToken = $this->coreAPI->GetOAuthToken($this->loginFilePath);
        $this->compareResults($filePath, $this->accessToken, true);
    }

现在所有这些功能都在做同样的事情。

1 个答案:

答案 0 :(得分:0)

我在这里看到两种可能的解决方案:

正如axiac在评论中所建议的那样,您可以使用数据提供者。

数据提供程序是一种返回参数数组的方法,可以使用不同的参数多次调用测试方法。有关详细信息,请参阅PHPUnit documentation about data providers

/**
 * @dataProvider provideGetGifts
 * @param $filename
 */
public function testGetGifts($fileName) {
    $filePath = $this->path . $fileName;
    $this->accessToken = $this->coreAPI->GetOAuthToken($this->loginFilePath);
    $this->compareResults($filePath, $this->accessToken, true);
}


public function provideGetGifts()
{
    return array(
        array('get-gifts-given-video.json'),
        array('get-gifts-received-audio.json'),
        array('get-gifts-received-video.json'),
    );
}

第二种解决方案,如果你想拥有不同的方法名,就是简单地使用第二种方法,其中包括一些测试逻辑:

protected function compareAccessTokenWithFilePath($fileName) {
    $filePath = $this->path . $fileName;
    $this->accessToken = $this->coreAPI->GetOAuthToken($this->loginFilePath);
    $this->compareResults($filePath, $this->accessToken, true);
}

public function testGetGiftsGivenVideo() {
    $this->compareAccessTokenWithFilePath('get-gifts-given-video.json');
}

public function testGetGiftsReceivedAudio() {
    $this->compareAccessTokenWithFilePath('get-gifts-given-audio.json');
}

public function testGetGiftsReceivedVideo() {
    $this->compareAccessTokenWithFilePath('get-gifts-received-video.json');
}

就个人而言,我更喜欢第一种解决方案。它更清晰一点。

相关问题