【问题标题】:Mocking a call with chained methods and arguments使用链式方法和参数模拟调用
【发布时间】:2014-07-08 00:27:13
【问题描述】:

我正在学习如何使用模拟来运行一些单元测试,但我不确定如何模拟我的数据库类。它由单独的方法组成,可以像这两个示例一样链接:

$db->select('someTblName',['fieldName'])
   ->where('fieldName', 'someValue')
   ->runQuery()
   ->fetch(); //returns array or null

另一种用法可能是:

$db->select('someTblName')
   ->where('fieldName', 'someValue')
   ->where('fieldName', array('>=' , 'someValue')
   ->runQuery()
   ->fetch(); //returns array or null

通过阅读一些文档,我发现我可以这样做:(对于第一种情况)

$db = \Mockery::mock('Database');
$db->shouldReceive('select', 'where', 'runQuery', 'fetcth')
    ->with(??????)
    ->andReturn(null);

现在我对如何将“相应”参数传递给方法感兴趣?而且,我将如何模拟第二种情况。

【问题讨论】:

    标签: php unit-testing mockery


    【解决方案1】:

    如果您不关心参数,您可以使用shouldReceive('select->where->runQuery->fetch')。如果您确实想检查参数,则必须执行以下操作来链接期望:

    $db->shouldReceive('select')->with('someTblName', ['fieldName'])
        ->once()->andReturn(m::self())->getMock()
        ->shouldReceive('where')...
    

    最后一个 shouldReceive 是shouldReceive('fetch')->andReturn(null)

    【讨论】:

    • 我最近学习了不关心参数的方法。不知道第二种方法谢谢
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-07-05
    • 1970-01-01
    • 2018-10-09
    • 1970-01-01
    • 2018-09-03
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多