phpunit: How do I pass values between tests?

前端 未结 4 548
礼貌的吻别
礼貌的吻别 2021-01-03 19:48

I\'m really running into a brick wall with this. How do you pass class values between tests in phpunit?

Test 1 -> sets value,

Test 2 -> reads value

H

4条回答
  •  萌比男神i
    2021-01-03 20:16

    The setUp() method is always called before tests, so even if you set up a dependency between two tests, any variables set in setUp() will be overwritten. The way PHPUnit data passing works is from the return value of one test to the parameter of the other:

    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);
        }
    }
    

    So if you need to save more state between tests, return more data in that method. I would guess that the reason PHPUnit makes this annoying is to discourage dependent tests.

    See the official documentation for details.

提交回复
热议问题