我正在寻找测试以下静态方法的最佳方法(特别是使用Doctrine模型):
class Model_User extends Doctrine_Record
{
public static function create($userData)
{
$newUser = new self();
$newUser->fromArray($userData);
$newUser->save();
}
}
理想情况下,我会使用模拟对象来确保调用了fromArray
(使用提供的用户数据)和save
,但这是不可能的,因为该方法是静态的。
有什么建议吗?
发布于 2014-02-21 02:32:00
现在有了AspectMock库来帮助实现这一点:
https://github.com/Codeception/AspectMock
$this->assertEquals('users', UserModel::tableName());
$userModel = test::double('UserModel', ['tableName' => 'my_users']);
$this->assertEquals('my_users', UserModel::tableName());
$userModel->verifyInvoked('tableName');
发布于 2017-11-19 21:48:17
我将在扩展Model_User
的单元测试命名空间中创建一个新类,并对其进行测试。下面是一个例子:
原始类:
class Model_User extends Doctrine_Record
{
public static function create($userData)
{
$newUser = new self();
$newUser->fromArray($userData);
$newUser->save();
}
}
要在单元测试中调用的模拟类:
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);
}
}
发布于 2018-07-25 16:07:38
doublit库还可以帮助您测试静态方法:
/* Create a mock instance of your class */
$double = Doublit::mock_instance(Model_User::class);
/* Test the "create" method */
$double::_method('create')
->count(1) // test that the method is called once
->args([Constraints::isInstanceOf('array')]) // test that first argument is an array
->stub('my_value') // stub the method to return "myvalue"
https://stackoverflow.com/questions/2357001
复制相似问题