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

标签 class phpunit

我真的遇到了这个问题。你如何在 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/

相关文章:

Android 全局/常用函数

swift - 在 swift 结构上改变类属性

c# - 显式和非显式 C# 类初始值设定项的区别

mocking - 在 phpunit 中创建模拟而不模拟任何方法?

PHPUnit Mock 稍后改变期望

php - 使用 phpunit 测试异常信息

java - 将 boolean 方法执行传递给另一个类 - java

android - 找不到扩展 View 的类?

PhpStorm & PHPUnit 6 : PhpStorm always creates PHPUnit templates for < 5

php - Selenium 不显示失败的数字行