我会在扩展Model_User并测试它的单元测试名称空间中创建一个新类。这里有一个例子:
原班:
class Model_User extends Doctrine_Record
{
public static function create($userData)
{
$newUser = new self();
$newUser->fromArray($userData);
$newUser->save();
}
}
模拟类调用在单元测试(S):
use \Model_User
class Mock_Model_User extends Model_User
{
/** \PHPUnit\Framework\TestCase */
public static $test;
// This class inherits all the original classes functions.
// However, you can override the methods and use the $test property
// to perform some assertions.
}
在你的单元测试:
use Module_User;
use PHPUnit\Framework\TestCase;
class Model_UserTest extends TestCase
{
function testCanInitialize()
{
$userDataFixture = []; // Made an assumption user data would be an array.
$sut = new Mock_Model_User::create($userDataFixture); // calls the parent ::create method, so the real thing.
$sut::test = $this; // This is just here to show possibilities.
$this->assertInstanceOf(Model_User::class, $sut);
}
}
来源
2017-11-19 13:48:17
b01
值得注意“这种方法只适用于调用者和被调用者在同一个类中的静态方法调用的存根和模拟,这是因为[静态方法是死于可测性](http://misko.hevery.com/2008/12/15/static-methods-are-death-to-testability/)。“ – 2012-10-01 15:30:59
从PHPUnit v4开始,'staticExpects'函数已被删除。请参阅[在github上的此线程](https://github.com/sebastianbergmann/phpunit-mock-objects/issues/137)以解释原因。 – 2015-11-28 00:51:35
因为我们知道'staticExpects'已经从PHPUnit的最新版本中移除了,那么在没有'staticExpects'的情况下实现这一点的替代方法是什么? – 2017-01-17 13:13:51