gpt4 book ai didi

php - PHPUnit 测试用例中的 Const

转载 作者:搜寻专家 更新时间:2023-10-31 20:44:42 26 4
gpt4 key购买 nike

我的 php 函数中有一个 const 限制,如下所示。

 const limit = 5 ;
function limit_check($no_of_page)
{
if($no_of_page < const limit)
return true; else return false;
}

现在我想使用 PHPUnit 为此编写单元用例,但在单元用例中我想重置限制,这样我的测试用例就不会在有人重置限制时失败。如何在我的单元测试函数中设置 php 常量?

最佳答案

通常,您出于编码原因设置了此限制,因此,您应该检查并强制执行此限制,因为它可能有存在的理由。但是,如果没有,那么您可能会得到更类似于以下内容的内容:

class FOO
{
const limit = 5;
private $PageNumberLimit;

public function __construct($PageLimit = self::limit)
{
$this->SetPageLimit($PageLimit);
}

public function SetPageLimit($PageLimit)
{
$this->PageNumberLimit = $PageLimit;
}

public function limit_check($no_of_page)
{
if($no_of_page < $this->PageNumberLimit)
return true;
else
return false;
}
}

然后是测试:

class FOO_TEST extends PHPUnit_Framework_TestCase
{
protected $FooClass;

protected function setUp()
{
$this->FooClass = new FOO();
}

public function testConstantValue()
{
$ReflectObject = new ReflectionClass('FOO');
$this->assertEquals(5, $ReflectObject->getConstant('limit'), 'Test that the default Page Limit of 5 was not changed');
}

public function testDefaultLimitUsed()
{
$ReflectObject = new ReflectionClass('FOO');
$this->assertEquals($ReflectObject->getConstant('limit'), $this->FooClass->PageNumberLimit, 'Test that the default Page Limit is used by matching value to constant.');
}

public function testlimit_check()
{
$this->assertTrue($this->FooClass->limit_check(4), 'Page Number is less than Limit');
$this->assertFalse($this->FooClass->limit_check(5), 'Page Number is equal to Limit');
$this->assertFalse($this->FooClass->limit_check(6), 'Page Number is greater than Limit');
}

public static function PageNumberDataProvider()
{
return array(
array(4),
array(5),
array(6),
);
}

/**
* @dataProvider PageNumberDataProvider
*/
public function testSetPageLimitWithConstructor($NumberOfPages)
{
$Foo = new FOO($NumberOfPages); // Create the class using the constructor

$this->assertTrue($Foo->limit_check($NumberOfPages - 1), 'Page Number is less than Limit');
$this->assertFalse($Foo->limit_check($NumberOfPages), 'Page Number is equal to Limit');
$this->assertFalse($Foo->limit_check($NumberOfPages + 1), 'Page Number is greater than Limit');
}

/**
* @dataProvider PageNumberDataProvider
*/
public function testSetPageLimitWithSetPageLimit($NumberOfPages)
{
$this->FooClass->SetPageLimit($NumberOfPages); // Set the number using the public function

$this->assertTrue($Foo->limit_check($NumberOfPages - 1), 'Page Number is less than Limit');
$this->assertFalse($Foo->limit_check($NumberOfPages), 'Page Number is equal to Limit');
$this->assertFalse($Foo->limit_check($NumberOfPages + 1), 'Page Number is greater than Limit');
}
}

关于php - PHPUnit 测试用例中的 Const,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14680862/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com