Skip to content

Instantly share code, notes, and snippets.

@johnkary
Created October 19, 2010 20:27
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save johnkary/635035 to your computer and use it in GitHub Desktop.
Save johnkary/635035 to your computer and use it in GitHub Desktop.
What is best practice for building a mock used across several tests?
<?php
/**
* Having trouble building the same mock in my setUp() method.
* What is best practice for building a mock used across several tests?
*
* Error:
* 1) SystemUnderTestTest::testSecondTest
* PHPUnit_Framework_Exception: Class "MockStaffCredential" already exists.
*/
class SystemUnderTest
{
}
class BaseCredential
{
public function calculate($var)
{
}
}
class SystemUnderTestTest extends PHPUnit_Framework_TestCase
{
protected $object;
public function setUp()
{
$this->object = new SystemUnderTest;
$this->mockPermission = $this->buildMockCredential('MockStaffCredential');
}
protected function buildMockCredential($mockClassName)
{
$mock = $this->getMock('BaseCredential', array(), array(), $mockClassName);
$mock->expects($this->any())
->method('calculate')
->will($this->returnValue(true));
return $mock;
}
//Passes just fine
public function testFirstTest()
{
$this->assertTrue($mockPermission->calculate(1));
}
//Error:
//1) SystemUnderTestTest::testSecondTest
//PHPUnit_Framework_Exception: Class "MockStaffCredential" already exists.
public function testSecondTest()
{
$this->assertTrue($mockPermission->calculate(2));
}
}
?>
@alex-moreno
Copy link

as far as i've rode, something like that:

    if(!class_exists($mockClassName)){

viewed in: http://www.sitepoint.com/forums/showthread.php?512513-PHPUnit-is-very-frustrating

Thanks

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment