【问题标题】:Why can't create mock per class?为什么不能为每个班级创建模拟?
【发布时间】:2020-07-17 13:44:14
【问题描述】:

我正在尝试编写这个类的测试。



class Page
{
    private function getPage(){
        $curl = curl_init();

        curl_setopt_array($curl, array(
            CURLOPT_URL => "http://example.com/",
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_ENCODING => "",
            CURLOPT_MAXREDIRS => 10,
            CURLOPT_TIMEOUT => 30,
            CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
            CURLOPT_CUSTOMREQUEST => "GET",
            CURLOPT_POSTFIELDS => "",
            CURLOPT_HTTPHEADER => array(
                "cache-control: no-cache"
            ),
        ));

        $response = curl_exec($curl);
        $err = curl_error($curl);

        curl_close($curl);

        return $response;

    }

    public function getTitle()
    {
        $page = $this->getPage();
        $re = '/(<title>)(.*?)(<\/title>)/m';
        preg_match_all($re, $page, $matches, PREG_SET_ORDER, 0);
        return $matches[0][2];
    }
}

而且由于我的getPage方法访问的是外部资源,所以我需要为它构建Mock

namespace Tests;
use PHPUnit\Framework\TestCase;
use App\Kernel\Page;

class PageTest extends TestCase
{
    public function testGetTitle()
    {
        $stub = $this->createMock(Page::class);
        $stub->method('getPage')
            ->willReturn('<title>Example Domain</title>');
        $this->assertSame('Example Domain', $stub->getTitle());
    }
}

当我调用测试时出现错误:

1) 测试\PageTest::testGetTitle 尝试配置无法配置的方法“getPage”,因为它不存在、尚未指定、是最终的或静态的

我看了那里的测试示例,他们说要这样做,但是为什么会发生错误,我不记得了 - 谁能告诉我如何测试这样的代码?

【问题讨论】:

标签: php phpunit


【解决方案1】:

测试私有方法的最好方法是不要模拟它们或改变它们的可见性,你应该测试委托私有方法的方法,在这种情况下,你应该调用 getTitle。或者以某种方式触发一个方法来查看该私有方法的副作用(你做得很好)。但是你可以看到 getTitle 方法什么也没做,它只是调用 getPage 方法。我可以建议你做的是模拟 curl_init ,在这种情况下这是不可能的,但你可以使用这个包来模拟它。 https://github.com/php-mock/php-mock-phpunit。或者您可以将 getPage 内容移动到一个单独的类并将其用作页面类中的依赖注入,然后您可以模拟该类并期望适当的期望。您还可以查看如何对 curl 调用 how to unit test curl call in php 进行单元测试的示例

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-03-09
    • 2023-03-23
    • 1970-01-01
    • 1970-01-01
    • 2017-07-15
    相关资源
    最近更新 更多