Reputation: 391
I have a const limit in my php function as given below.
const limit = 5 ;
function limit_check($no_of_page)
{
if($no_of_page < const limit)
return true; else return false;
}
Now I want to write the unit cases for this using PHPUnit, but in unit cases I want to reset the limit so that my test cases not fail if someone resets limit. How to set the php const in my unit test function?
Upvotes: 3
Views: 4546
Reputation: 11250
Normally, you have set this limit for a coding reason, and therefore, you should check and enforce this limit as it likely has a reason for being there. However, if not, then you could have something more like the following:
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;
}
}
Then the tests:
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');
}
}
Upvotes: 3