首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >PHPUnit模拟对象和静态方法

PHPUnit模拟对象和静态方法
EN

Stack Overflow用户
提问于 2010-03-01 23:49:00
回答 6查看 82.9K关注 0票数 58

我正在寻找测试以下静态方法的最佳方法(特别是使用Doctrine模型):

代码语言:javascript
复制
class Model_User extends Doctrine_Record
{
    public static function create($userData)
    {
        $newUser = new self();
        $newUser->fromArray($userData);
        $newUser->save();
    }
}

理想情况下,我会使用模拟对象来确保调用了fromArray (使用提供的用户数据)和save,但这是不可能的,因为该方法是静态的。

有什么建议吗?

EN

回答 6

Stack Overflow用户

发布于 2014-02-21 02:32:00

现在有了AspectMock库来帮助实现这一点:

https://github.com/Codeception/AspectMock

代码语言:javascript
复制
$this->assertEquals('users', UserModel::tableName());   
$userModel = test::double('UserModel', ['tableName' => 'my_users']);
$this->assertEquals('my_users', UserModel::tableName());
$userModel->verifyInvoked('tableName'); 
票数 14
EN

Stack Overflow用户

发布于 2017-11-19 21:48:17

我将在扩展Model_User的单元测试命名空间中创建一个新类,并对其进行测试。下面是一个例子:

原始类:

代码语言:javascript
复制
class Model_User extends Doctrine_Record
{
    public static function create($userData)
    {
        $newUser = new self();
        $newUser->fromArray($userData);
        $newUser->save();
    }
}

要在单元测试中调用的模拟类:

代码语言:javascript
复制
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.
}

在你的单元测试中:

代码语言:javascript
复制
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);
    }
}
票数 4
EN

Stack Overflow用户

发布于 2018-07-25 16:07:38

doublit库还可以帮助您测试静态方法:

代码语言:javascript
复制
/* 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"
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/2357001

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档