drgawfsf1069 2015-01-12 17:58
浏览 45
已采纳

是否可以使用普通的PHP或Mockery覆盖类的方法?

My question would be best illustrated by the following example:

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());
    }
}

Let me point out that I don't have the control over where class 'a' is being defined/included.

  • 写回答

2条回答 默认 最新

  • duanjia4969 2015-01-12 18:48
    关注

    If you changed class b so that the instance of a can be passed in:

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

    ...then for test, you can use a framework like Mockery to pass in a mocked instance of 'a' which always returns '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());
        }
    
    }
    

    See the full docs and examples for Mockery here: http://docs.mockery.io/en/latest/getting_started/simple_example.html

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥50 C++使用TWAIN协议如何实现A3幅面扫描仪扫描A4横向
  • ¥15 如何在sql server里完成筛选
  • ¥15 请问为什么我配置IPsec后PC1 ping不通 PC2,抓包出来数据包也并没有被加密
  • ¥200 求博主教我搞定neo4j简易问答系统,有偿
  • ¥15 nginx的使用与作用
  • ¥100 关于#VijeoCitect#的问题,如何解决?(标签-ar|关键词-数据类型)
  • ¥15 一个矿井排水监控系统的plc梯形图,求各程序段都是什么意思
  • ¥50 安卓10如何在没有root权限的情况下设置开机自动启动指定app?
  • ¥15 ats2837 spi2从机的代码
  • ¥200 wsl2 vllm qwen1.5部署问题