如何使用PHPUnit模拟强类型服务依赖项?

时间:2014-11-17 11:37:56

标签: mocking phpunit

我有服务:

<?php
class MyService {

    private $dependency;

    function __construct(IDependency $dependency)
    {
        $this->dependency = $dependency;
    }

    public function testableMethod($someArgument)
    {
        $this->dependency->doSomething($someArgument);
    }
}

我想在我的PHPUnit单元测试中模拟IDependency并验证该方法是否被调用:

<?php
class MyServiceTest extends \PHPUnit_Framework_TestCase {

    public function test_testableMethod_callsDependency(){
        $mock = $this->getMock('IDependency');
        $mock->method('doSomething')->willReturn('some stuff');
        $sut = new MyService($mock);

        $sut->isFileDownloadUrl('some argument');

        $mock->expects($this->once())
            ->method('doSomething')
            ->with($this->equalTo('some argument'));
    }
}

这导致:

ErrorException: Argument 1 passed to FileDownloadService::__construct() must be an instance of IDependency, instance of Mock_IDependency_46fe6bd6 given, called in /yadda//yadda/MyService.php on line 12 and defined

有没有办法在PHPUnit中处理这个问题?或者我需要另一个工具吗?或者我是否必须为强类型签名创建自己的模拟?

1 个答案:

答案 0 :(得分:0)

原来这是100%可能的,我在其他地方做了一个booboo。确保接口正确:

$mock = $this->getMock('My\Namespace\IDependency');