我正在为一个类编写单元测试,如下所示:

class example {

    public function __construct($param1, $param2) {
        $this->param1 = $param1
        $this->param2 = $param2
    }
}


执行构造函数后,是否可以测试$ this-> param1和$ this-> param2是否存在?我已经用谷歌搜索了,但是没有找到有效的答案。我用Assertion contain尝试过,但这也没有用。

最佳答案

如果要查看是否在结果对象中为属性分配了指定的值,请使用Reflection class。在您的示例中,如果您的属性是公共的:

public function testInitialParams()
{
    $value1 = 'foo';
    $value2 = 'bar';
    $example = new Example($value1, $value2); // note that Example is using 'Standing CamelCase'
    $sut = new \ReflectionClass($example);

    $prop1 = $sut->getProperty('param1');
    $prop1->setAccessible(true); // Needs to be done to access protected and private properties
    $this->assertEquals($prop2->getValue($example), $value1, 'param1 got assigned the correct value');

    $prop2 = $sut->getProperty('param2');
    $prop2->setAccessible(true);
    $this->assertEquals($prop2->getValue($example), $value2, 'param2 got assigned the correct value');
}

关于php - 如何使用phpunit测试变量是否存在于函数中,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/39701882/

10-13 06:04
查看更多