phpunit:如何在测试之间传递值?

Dra*_*sil 22 phpunit class

我真的碰到了这堵砖墙.如何在phpunit中的测试之间传递类值?

测试1 - >设定值,

测试2 - >读取值

这是我的代码:

class JsonRpcBitcoinTest extends PHPUnit_Framework_TestCase
{
    public function setUp(){
        global $configRpcUser, $configRpcPass, $configRpcHost, $configRpcPort;

        $this->bitcoindConn = new JsonRpcBitcoin($configRpcUser, $configRpcPass, $configRpcHost, $configRpcPort);
        $this->blockHash = '';
    }

    /**
    * @depends testCanAuthenticateToBitcoindWithGoodCred
    */
    public function testCmdGetBlockHash()
    {   
        $result = (array)json_decode($this->bitcoindConn->getblockhash(20));
        $this->blockHash = $result['result'];
        $this->assertNotNull($result['result']);
    }

    /**
    * @depends testCmdGetBlockHash
    */
    public function testCmdGetBlock()
    {   
        $result = (array)json_decode($this->bitcoindConn->getblock($this->blockHash));
        $this->assertEquals($result['error'], $this->blockHash);
    }
}
Run Code Online (Sandbox Code Playgroud)

testCmdGetBlock()没有得到$this->blockHash应该设置的值testCmdGetBlockHash().

非常感谢帮助理解错误.

Ano*_*ous 37

setUp()方法总是在测试之前调用,因此即使您在两个测试之间设置了依赖关系,任何设置的变量都setUp()将被覆盖.PHPUnit数据传递的工作方式是从一个测试的返回值到另一个测试的参数:

class JsonRpcBitcoinTest extends PHPUnit_Framework_TestCase
{
    public function setUp()
    {
        global $configRpcUser, $configRpcPass, $configRpcHost, $configRpcPort;

        $this->bitcoindConn = new JsonRpcBitcoin($configRpcUser, $configRpcPass, $configRpcHost, $configRpcPort);
        $this->blockHash = '';
    }


    public function testCmdGetBlockHash()
    {   
        $result = (array)json_decode($this->bitcoindConn->getblockhash(20));
        $this->assertNotNull($result['result']);

        return $result['result']; // the block hash
    }


    /**
     * @depends testCmdGetBlockHash
     */
    public function testCmdGetBlock($blockHash) // return value from above method
    {   
        $result = (array)json_decode($this->bitcoindConn->getblock($blockHash));
        $this->assertEquals($result['error'], $blockHash);
    }
}
Run Code Online (Sandbox Code Playgroud)

因此,如果您需要在测试之间保存更多状态,请在该方法中返回更多数据.我猜想PHPUnit使这个烦人的原因是阻止依赖测试.

详情请参阅官方文档.

  • 您可能会强调您指的是“@depends”注释,我花了一段时间才弄清楚......无论如何都是很好的答案 (2认同)

qua*_*ous 9

你可以在一个函数中使用一个静态变量... PHP烦人地与所有实例共享类方法的静态变量......但是在这个cas中它可以帮助:p

protected function &getSharedVar()
{
    static $value = null;
    return $value;
}

...

public function testTest1()
{
    $value = &$this->getSharedVar();

    $value = 'Hello Test 2';
}


public function testTest2()
{
    $value = &$this->getSharedVar();

    // $value should be ok
}
Run Code Online (Sandbox Code Playgroud)

注意:这不是好方法,但如果您在所有测试中都需要一些数据,它会有所帮助......

  • “ PHP与所有实例烦人地共享类方法的静态变量” –这就是静态变量的全部观点!正是为了这个目的而存在它们,以便在类的所有实例之间共享值。我不明白为什么这会令人讨厌,如果您不希望这样做,则不要使用静态变量。请阅读有关PHP中静态变量的文档。 (2认同)