【问题标题】:how to test if variables exists in function with phpunit如何使用phpunit测试函数中是否存在变量
【发布时间】:2016-09-26 11:40:55
【问题描述】:

我正在为一个看起来像这样的类编写单元测试:

class example {

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

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

【问题讨论】:

    标签: php unit-testing testing phpunit this


    【解决方案1】:

    如果要查看结果对象中的属性是否已分配指定值,请使用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');
    }
    

    【讨论】:

    • 这不起作用,收到此错误消息:不是预期类“ReflectionProperty”的实例
    • 糟糕,等待修复 :-)
    • @nova 这行得通。忘记了使用反射并不是那么简单。
    • $this->assertEquals($sut->getProperty('param1')->getValue($example), $value1, 'param1 得到了正确的值');仍然不起作用只有prop2
    • 如相邻答案中所述,这取决于您的属性的可见性类型。如果$param1 是受保护/私有的,那么->setAccessible(true); 是访问这些属性所必需的。
    【解决方案2】:

    有一个断言assertAttributeSame() 允许您查看类的公共、受保护和私有属性。

    看例子:

    class ColorTest extends PHPUnit_Framework_TestCase {
    public function test_assertAttributeSame() {
    
        $hasColor = new Color();
    
        $this->assertAttributeSame("red","publicColor",$hasColor);
        $this->assertAttributeSame("green","protectedColor",$hasColor);
        $this->assertAttributeSame("blue","privateColor",$hasColor);
    
        $this->assertAttributeNotSame("wrong","privateColor",$hasColor);
        }
    
    }
    

    【讨论】:

    • 仅供参考,这些方法在 PHPUnit 8 中已弃用,将在 PHPUnit 9 中删除。
    • @duncan - 很高兴知道!
    【解决方案3】:

    您尚未在 $this->param1$this->param2 上声明任何可见性,因此默认情况下它们是公开的。

    考虑到这一点,您应该能够像以下那样进行测试:

    public function testConstructorSetsParams()
    {
        $param1 = 'testVal1';
        $param2 = 'testVal2';
    
        $object = new example($param1, $param2);
    
        $this->assertEquals($param1, $object->param1);
        $this->assertEquals($param2, $object->param2);
    }
    

    【讨论】:

    • 不能访问非公开成员,需要先设置为可访问
    • 嗯,对我有用。您是否对属性设置了任何可见性限制?
    猜你喜欢
    • 2021-12-08
    • 1970-01-01
    • 1970-01-01
    • 2012-03-04
    • 1970-01-01
    • 2014-02-10
    • 1970-01-01
    • 1970-01-01
    • 2011-08-05
    相关资源
    最近更新 更多