以下示例将最好地说明我的问题:

class a
{
    function a()
    {
         return file_get_contents('http://some/third/party/service');
    }
}

class b
{
    function b()
    {
        $a = new a();
        return $a->a() . ' Bar';
    }
}

class testB extends test
{
    function testB()
    {
        $b = new b();

        // Here we need to override a::a() method in some way to always return 'Foo'
        // so it doesn't depend on the third party service. We only need to check
        // the $b::b() method's behavior (that it appends ' Bar' to the string).
        // How do we do that?

        $this->assert_equals('Foo Bar', $b->b());
    }
}


我要指出的是,我无法控制在何处定义/包含类“ a”。

最佳答案

如果更改了类b以便可以传入a的实例:

class b
{
    function b($a = null)
    {
        if ($a == null) {
            $a = new a();
        }

        return $a->a() . ' Bar';
    }
}


...然后进行测试,您可以使用Mockery之类的框架来传递模拟的实例“ a”,该实例始终返回“ Foo”

use \Mockery as m;

class testB extends test
{

    public function tearDown()
    {
        m::close();
    }

    public function testB()
    {
        $mockA = m::mock('a');
        $mockA->shouldReceive('a')->times(1)->andReturn('foo');

        $b = new b($mockA);

        $this->assert_equals('Foo Bar', $b->b());
    }

}


在此处查看Mockery的完整文档和示例:http://docs.mockery.io/en/latest/getting_started/simple_example.html

10-07 15:04