php - 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.
解决方案
摆脱:
错误:调用未定义的方法 MainNavTest::assertStringContainsString()
IIRC 删除:
function __construct(){
parent::__construct();
$this->Model = new Model();
}
从测试用例应该成功。
该方法通常是 Phpunit 的一部分,请参阅Phpunit 手册中的断言
并且不要 在您的测试用例中重新引入任何方法。 __construct()
如果您不想在具体的测试用例方法中进行设置,请使用合适的钩子方法,例如setUp
我猜你的情况:
function setUp(): void
{
parent::setUp();
$this->Model = new Model();
}
推荐阅读
- unity3d - 通过 vofuria 和 unity 跟踪真实物体的运动,忽略相机的运动
- mysql - 当我在查询中添加位置时,它现在显示计数 0
- javascript - 尝试检查已打印的项目并打印除此之外的项目
- c# - localdb 创建新行空异常
- python - Jupyter笔记本回车不起作用
- pgp - 使用 PGP 密钥通过 curl api 进行 Vault 初始化失败
- amazon-s3 - 有没有办法实时查看 S3 上的 ALB 访问日志?
- android - 在真实设备上进行测试时,uses-library com.android.nfc_extras 会破坏 API 26 及更高版本的 AndroidTest
- java - Spring Validator 将日期与数据库中的另一个日期进行比较
- java - 如何从 Java 应用程序连接到 Heroku 上的 Bonsai ElasticSearch