【问题标题】:PHPUnit: How to Test a single Function in an Helper filePHPUnit:如何在 Helper 文件中测试单个函数
【发布时间】:2021-07-25 17:55:15
【问题描述】:

我想在帮助文件中测试一个新函数。

function isProductionSite() {
    return !(bool) preg_match('/admin|development/', request()->getHttpHost());
}

当我在我的测试函数中调用这个函数时,我得到了我的本地地址。因此我试图模拟 request()->getHttpHost.

public function testIsProductionSiteExpectFalse(): void
{
    $request = Mockery::mock(Request::class);
    $request->shouldReceive('getHttpHost')->once()->andReturn('admin.mydomain.de');
    $this->assertFalse(isProductionSite());
}

在 Tets 函数中,$request->getHttpHost() 现在将输出 admin.mydomain.de。但是要测试的函数中的 getHttpHost() (isProductionSite()) 为我提供了正确的主机。

如何在测试用例中设置 HttpHost,以便帮助函数输出被操纵的主机?

【问题讨论】:

    标签: unit-testing testing mocking phpunit


    【解决方案1】:

    您正在模拟 $request 的实例,但被测函数使用的实例不是模拟,而可能是一个全局变量。

    应始终将依赖项传递给辅助函数。只需将$request 添加为isProductionSite 的参数即可。

    【讨论】:

    • 感谢您的回答和好建议!
    • 很高兴这个答案很有用。如果您认为答案解决了问题,请记住将答案标记为已接受。
    猜你喜欢
    • 2016-09-21
    • 2014-02-10
    • 1970-01-01
    • 2014-08-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-05-21
    • 2012-04-01
    相关资源
    最近更新 更多