简体   繁体   English

返回参数被发送到Mockery模拟函数吗?

[英]Return arguments being sent to a Mockery mocked function?

I'm rather new to the PHP Mockery framework, and attempting to test multiple functions on a mocked service request function. 我是PHP Mockery框架的新手,尝试在模拟服务请求功能上测试多个功能。 The different functions send the same variable names with different values. 不同的函数发送具有不同值的相同变量名。 I'd like to test to make sure each case is hitting the mocked class. 我想测试一下,以确保每种情况都符合模拟的要求。 Can I receive multiple arguments with my mocked function and return each of them to the tester function? 我可以通过模拟函数接收多个参数,然后将每个参数返回给测试器函数吗?

The function to test: 测试功能:

    public function doSomething() {
    $result = $this->serviceRequest('stuff', '/url', []);
    return $result;
}

The pseudocode for testing function: 用于测试功能的伪代码:

public function testDoSomething() {

    $service_mock = $this->mockService();
    $this->assertEquals($service_mock->doSomething(), $returnedArgs);
}

I'd ideally like to take those three arguments being sent to the mock, return them with the mock's andReturn() or something similar to be asserted in the original test method (to verify they are being sent to the mock). 理想情况下,我想将这三个参数发送给模拟,并使用模拟的andReturn()或与原始测试方法中声明的类似内容返回它们(以验证是否将它们发送给模拟)。 Is there a good way to do this or a common practice I'm missing? 有没有一个好的方法可以做到这一点,或者我错过了一个常见的做法?

Right now, my mock is looking similar to this pseudocode (and those 3 arguments are being validated in closure $args ): 现在,我的模拟看起来与此伪代码相似(并且这三个参数正在$args闭包中进行验证):

        $client->shouldReceive('serviceRequest')->withArgs($args)->once()->andReturnUsing($args)->getMock();

Thanks! 谢谢!

You can use a callback to do this: The below example is adapted form the Mockery docs, although it uses it as an example for reference passing, it can be used for any custom expectations. 您可以使用回调来执行此操作:下面的示例是Mockery文档的改编而成,尽管该示例将其用作传递引用的示例,但也可以用于任何自定义期望。

   $m->shouldReceive('insert')->with(
    \Mockery::on(function(&$data) use($logger) {
        if (!is_array($data)) return false;
        $data['_id'] = 123;
        $logger->logParameters('insert', $data);
        return true;
    }),
    \Mockery::any()
);

http://docs.mockery.io/en/latest/reference/pass_by_reference_behaviours.htm http://docs.mockery.io/en/latest/reference/pass_by_reference_behaviours.htm

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM