Mockery 解决“PHP单元测试中类方法强依赖问题”

栏目: PHP · 发布时间: 5年前

内容简介:当我们对一个有一定时间的项目进行单元测试的时候,会遇到这样的问题。new 的声明在项目代码里随处可见,通过这种方式实例化对象的代码并不容易去编写测试代码。最简单的回答是,重构您的代码。但这说起来简单,但做起来过程量相当大。如果重构是一种选择,那就去做吧。如果没有,可以考虑使用 Mockery 解决代码强依赖问题。

当我们对一个有一定时间的项目进行单元测试的时候,会遇到这样的问题。new 的声明在项目代码里随处可见,通过这种方式实例化对象的代码并不容易去编写测试代码。

最简单的回答是,重构您的代码。但这说起来简单,但做起来过程量相当大。

如果重构是一种选择,那就去做吧。如果没有,可以考虑使用 Mockery 解决代码强依赖问题。

文档: http://docs.mockery.io/en/latest/cookbook/mocking_hard_dependencies.html

以下是一个例子

<?php
namespace App;

class Service
{
    function callExternalService($param)
    {
        $externalService = new Service\External();
        $externalService->sendSomething($param);
        return $externalService->getSomething();
    }
}

解决方案

<?php
namespace AppTest;
use Mockery as m;
/**
 * @runTestsInSeparateProcesses
 * @preserveGlobalState disabled
 */
class ServiceTest extends \PHPUnit_Framework_TestCase {
    public function testCallingExternalService()
    {
        $param = 'Testing';
 
        $externalMock = m::mock('overload:App\Service\External');
        $externalMock->shouldReceive('sendSomething')
            ->once()
            ->with($param);
        $externalMock->shouldReceive('getSomething')
            ->once()
            ->andReturn('Tested!');
 
        $service = new \App\Service();
 
        $result = $service->callExternalService($param);
 
        $this->assertSame('Tested!', $result);
    }
}

@runTestsInSeparateProcesses 和 @preserveGlobalState disabled 的作用是让 phpunit 在独立的进程里执行以上的单元测试。

避免因为 Instance Mock 和原有类的单元测试相冲突导致抛出“class already exists”的异常

可能遇到的问题

执行 phpunit 抛出 Unable to spawn worker process 异常

@runTestsInSeparateProcesses 依赖函数 proc_open ,禁用后会报错。

解决方案:执行脚本时设置 disable_functions 为空,或者修改 php.ini 配置。

Mockery 解决“PHP单元测试中类方法强依赖问题”

xdebug 无法调试

如需 xdebug ,请修改测试类的 @runTestsInSeparateProcesses 的 @,让其失效。


以上所述就是小编给大家介绍的《Mockery 解决“PHP单元测试中类方法强依赖问题”》,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对 码农网 的支持!

查看所有标签

猜你喜欢:

本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们

Distributed Algorithms

Distributed Algorithms

Wan Fokkink / The MIT Press / 2013-12-6 / USD 40.00

This book offers students and researchers a guide to distributed algorithms that emphasizes examples and exercises rather than the intricacies of mathematical models. It avoids mathematical argumentat......一起来看看 《Distributed Algorithms》 这本书的介绍吧!

XML 在线格式化
XML 在线格式化

在线 XML 格式化压缩工具

Markdown 在线编辑器
Markdown 在线编辑器

Markdown 在线编辑器

html转js在线工具
html转js在线工具

html转js在线工具