提问人:Rizeen 提问时间:8/31/2023 最后编辑:ADysonRizeen 更新时间:8/31/2023 访问量:34
PHP PHPUnit 测试用例
PHP PHPUnit Test Case
问:
编写一个类“Skill”,用于处理以“has_”关键字开头的任何函数,返回函数“exist”,以及以任何应返回“不存在”的单词开头的任何其他函数,并检查属性,如果它以“_CT”结尾,则返回属性的 md5 加密,否则返回不加密。
我使用过魔术函数和面向对象编程。
以下是包含类技能和测试用例代码的文件:
技能.php
<?php declare(strict_types=1);
namespace Exam;
class Skill
{
public function __call($name, $args)
{
if (str_starts_with($name, 'has')) {
return true;
} else {
return false;
}
if (str_ends_with($args, 'CT')) {
return true;
} else {
return false;
}
}
}
技能测试 .php
<?php
use Coalition\Exam\Skill;
use PHPUnit\Framework\TestCase;
class SkillTest extends TestCase
{
public function testHasFunctionExists(): void
{
$skill = new Skill();
$function = 'has' . $this->generateRandomString(5);
$this->assertTrue($skill->$function(), 'success');
}
public function testHasPropertyExists(): void
{
$skill = new Skill();
$property = $this->generateRandomString(7) . '_CT';
$this->assertTrue($skill->$property == md5($property), 'success');
}
public function testHasAnyPropertyExists(): void
{
$skill = new Skill();
$property = $this->generateRandomString(7);
$this->assertFalse($skill->$property == md5($property), 'success');
}
public function testObjectAsString(): void
{
$skill = new Skill();
$this->assertTrue( strpos($skill, 'CT') !== false, 'success');
}
public function testSetSkillLanguage(): void
{
$skill = new Skill();
$skill->language = 'PHP';
$this->assertTrue( $skill->language === 'PHP', 'success');
}
public function testInvoke(): void
{
$skill = new Skill();
$this->assertEquals(10, $skill([3,7]));
}
private function generateRandomString($length = 10): string
{
$characters = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
$charactersLength = strlen($characters);
$randomString = '';
for ($i = 0; $i < $length; $i++) {
$randomString .= $characters[rand(0, $charactersLength - 1)];
}
return $randomString;
}
}
当我运行 PHPUnit 测试时,我收到错误。
有 2 个错误:
1)
SkillTest::testObjectAsString 类型错误:strpos():参数 #1 ($haystack) 必须是字符串类型,Coalition\Exam\Skill given
C:\xampp\htdocs\Rizeen-CT\tests\SkillTest.php:34
SkillTest::testInvoke 错误:Coalition\Exam\Skill 类型的对象是 不可调用
C:\xampp\htdocs\Rizeen-CT\tests\SkillTest.php:48
有 1 次失败:
SkillTest::testHasPropertyExists 成功 断言 false 失败 是真的。
C:\xampp\htdocs\Rizeen-CT\tests\SkillTest.php:20
错误!测试: 6, 断言: 4, 错误: 2, 失败: 1, 警告: 2, 弃用: 1.
我尝试将第一个参数声明为字符串,但错误仍然存在。
答: 暂无答案
评论
$skill
strpos($skill, 'CT') !== false
$skill([3,7])
$skill
$skill->$property == md5($property)
Write a class 'Skill' that handles any function which starts with ‘has_’ keyword return function ‘exist’ and any other function that starts with any word that should return ‘not exist’ and checking a property if it ends with ‘_CT’ return md5 encryption for property otherwise return without encryption