我真的遇到了这个问题。你如何在 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 让人讨厌的原因是不鼓励依赖测试。
See the official documentation for details .
关于class - phpunit:如何在测试之间传递值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31909785/