【问题标题】:PHPUnit and mocking dependenciesPHPUnit 和模拟依赖项
【发布时间】:2020-12-09 19:51:08
【问题描述】:

我正在为 Service 类编写一个测试。如下所示,我的 Service 类使用 Gateway 类。我想在我的一项测试中模拟 Gateway 类上 getSomething() 的输出。

我尝试使用存根 (createStub) 和模拟 (getMockBuilder),但 PHPUnit 没有产生预期的结果。

我的课:

<?php

class GatewayClass
{
    private $client = null;

    public function __construct(Client $client)
    {
        $this->client = $client->getClient();
    }

    public function getSomething()
    {
        return 'something';
    }
}

<?php

class Service
{
    private $gateway;

    public function __construct(Client $client)
    {
        $this->gateway = new Gateway($client);
    }

    public function getWorkspace()
    {
        return $this->gateway->getSomething();
    }
}

(这个项目还没有DI容器)

【问题讨论】:

    标签: php mocking phpunit


    【解决方案1】:

    要模拟您的Gateway 类,您必须将其注入Service

    class Service
    {
        private $gateway;
    
        public function __construct(Gateway $gateway)
        {
            $this->gateway = $gateway;
        }
    
        public function getWorkspace()
        {
            return $this->gateway->getSomething();
        }
    }
    
    class ServiceTest
    {
        public function test()
        {
            $gateway = $this->createMock(Gateway::class);
            $gateway->method('getSomething')->willReturn('something else');
            $service = new Service($gateway);
    
            $result = $service->getWorkspace();
    
            self::assertEquals('something else', $result);
        }
    }
    

    【讨论】:

    • 谢谢,createMockcreateStub 之间有什么区别吗?我自己尝试使用存根,但请注意您使用的是模拟。
    • Stub 实际上是正确的术语。 createStub 方法相当新,我还没有完全采用它。从技术上讲,您将从这两种方法中获得相同类型的对象(至少在当前版本的 PHPUnit 中),但最好区分不同类型的测试替身。以下是简要概述:martinfowler.com/bliki/TestDouble.html
    猜你喜欢
    • 2016-05-14
    • 1970-01-01
    • 2013-08-04
    • 1970-01-01
    • 1970-01-01
    • 2012-04-25
    • 2016-02-06
    • 2014-03-26
    • 2016-10-27
    相关资源
    最近更新 更多