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条)

报告相同问题?

悬赏问题

  • ¥15 c语言怎么用printf(“\b \b”)与getch()实现黑框里写入与删除?
  • ¥20 怎么用dlib库的算法识别小麦病虫害
  • ¥15 华为ensp模拟器中S5700交换机在配置过程中老是反复重启
  • ¥15 java写代码遇到问题,求帮助
  • ¥15 uniapp uview http 如何实现统一的请求异常信息提示?
  • ¥15 有了解d3和topogram.js库的吗?有偿请教
  • ¥100 任意维数的K均值聚类
  • ¥15 stamps做sbas-insar,时序沉降图怎么画
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看
  • ¥15 关于#Java#的问题,如何解决?