我真的碰到了这堵砖墙。如何在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);
}
}
testCmdGetBlock()
没有获得应该在$this->blockHash
中设置的testCmdGetBlockHash()
的值。
非常感谢帮助理解错误。
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);
}
}
因此,如果您需要在测试之间保存更多状态,请在该方法中返回更多数据。我猜想PHPUnit使这个烦人的原因是阻止依赖测试。
你可以在一个函数中使用一个静态变量... 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
}
注意:这不是好方法,但如果您在所有测试中都需要一些数据,它会有所帮助......