首页 > 解决方案 > PHP Protect property cannot be public but needed in Test

问题描述

In Result class, I must have a protected property $message, but when I run the code test in Maintest.php file, I can read the "successfully added set" message string inside the object, but because it is protected, I can't assert it against the actual object. I cannot make it public.

Please check the inline comments and ask me anything if you need more information

// Result.php

class Result
{   
    protected $message = ""; // must be protected

    static function success($message='')
    {
        return new Result ( 0, $message );
    }

    private function __construct( $message)
    {
        $this->message = $message;
    }


    public function getMessage(){
            return $message;
    }

}

Model.php

function addNewNavDbSet($set){
    $set = ModelSet::init($set["name"],$set["visibility"],$set["name"],$set["info"]);
    $this->ModelDbProvider->addNewSet($set);
    $this->getResult('Succesfully added Set');
    return Result::success ('Succesfully added Set'); // cannot access protected property, but I cannot make it public
}


function getResult($message) {
        return $message;
}

MainTest.php

class MainNavTest extends \PHPUnit\Framework\TestCase
{


    function __construct(){
        parent::__construct();
        $this->Model = new Model();
    }


    public function testSaveProperty()
    {
        $mySet = $this->Model->addNewSet("test ADD", 1,"hello world", "test", '1');
        var_dump($mySet); // returns object with string 'succesfully added set'.
        var_dump(Result::getMessage());
        $this->assertStringContainsString('Succesfully added Set', Result::getMessage());

    }
}

/tests/application/models/MainTest.php

Error: Call to undefined method MainNavTest::assertStringContainsString()

ERRORS! Tests: 1, Assertions: 0, Errors: 1.

标签: phpphpunit

解决方案


摆脱:

错误:调用未定义的方法 MainNavTest::assertStringContainsString()

IIRC 删除:

    function __construct(){
        parent::__construct();
        $this->Model = new Model();
    }

从测试用例应该成功。

该方法通常是 Phpunit 的一部分,请参阅Phpunit 手册中的断言

并且不要 在您的测试用例中重新引入任何方法。 __construct()

如果您不想在具体的测试用例方法中进行设置,请使用合适的钩子方法,例如setUp我猜你的情况:

    function setUp(): void
    {
        parent::setUp();
        $this->Model = new Model();
    }

请参阅Phpunit 手册中的 Fixtures


推荐阅读