PhpUnit 模拟一个内置函数

2023-10-31php开发问题
4

本文介绍了PhpUnit 模拟一个内置函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着跟版网的小编来一起学习吧!

问题描述

有没有办法在 PHPUnit 中模拟/覆盖内置函数 shell_exec.我知道 Mockery 并且我不能使用除了 PHPUnit 之外的其他库.我已经尝试了超过 3 小时并且卡在了某个地方.任何指针/链接将不胜感激.我正在使用 Zend-framework2

Is there a way to mock/override an inbuilt function shell_exec in PHPUnit. I am aware of Mockery and I cannot use other libraries apart from PHPUnit.I have tried for more than 3hrs and somewhere stuck. Any pointers / links would be highly appreciated. I am using Zend-framework2

推荐答案

有几个选项.例如,您可以在测试范围的命名空间中重新声明 php 函数 shell_exec.

There are several options. You could for example redeclare the php function shell_exec in the namespace of your test scope.

查看这篇很棒的博客文章以获取参考:PHP:模拟"单元测试中的 time() 等内置函数.

Check for reference this great blog post: PHP: "Mocking" built-in functions like time() in Unit Tests.

<php
namespace MyNamespace;

/**
 * Override shell_exec() in current namespace for testing
 *
 * @return int
 */
function shell_exec()
{
    return // return your mock or whatever value you want to use for testing
}
 
class SomeClassTest extends PHPUnit_Framework_TestCase
{ 
    /*
     * Test cases
     */
    public function testSomething()
    {
        shell_exec(); // returns your custom value only in this namespace
        //...
    }
}

现在,如果您在 MyNamespace 的类中使用全局 shell_exec 函数,它将使用您的自定义 shell_exec 函数.

Now if you used the global shell_exec function inside a class in the MyNamespace it will use your custom shell_exec function instead.

您还可以将模拟函数放在另一个文件中(与 SUT 具有相同的命名空间)并将其包含在测试中.像这样,如果测试具有不同的命名空间,您也可以模拟该函数.

You can also put the mocked function in another file (with the same namespace as the SUT) and include it in the test. Like that you can also mock the function if the test has a different namespace.

这篇关于PhpUnit 模拟一个内置函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

The End

相关推荐

PHP实现DeepL翻译API调用
DeepL的翻译效果还是很强大的,如果我们要用php实现DeepL翻译调用,该怎么办呢?以下是代码示例,希望能够帮到需要的朋友。 在这里需要注意,这个DeepL的账户和api申请比较难,不支持中国大陆申请,需要拥有香港或者海外信用卡才行,没账号的话,目前某宝可以...
2025-08-20 php开发问题
168

PHP通过phpspreadsheet导入Excel日期数据处理方法
PHP通过phpspreadsheet导入Excel日期,导入系统后,全部变为了4开头的几位数字,这是为什么呢?原因很简单,将Excel的时间设置问文本,我们就能看到该日期本来的数值,上图对应的数值为: 要怎么解决呢?进行数据转换就行,这里可以封装方法,或者用第三方的...
2024-10-23 php开发问题
287

mediatemple - 无法使用 codeigniter 发送电子邮件
mediatemple - can#39;t send email using codeigniter(mediatemple - 无法使用 codeigniter 发送电子邮件)...
2024-08-23 php开发问题
11

Laravel Gmail 配置错误
Laravel Gmail Configuration Error(Laravel Gmail 配置错误)...
2024-08-23 php开发问题
16

将 PHPMailer 用于 SMTP 的问题
Problem with using PHPMailer for SMTP(将 PHPMailer 用于 SMTP 的问题)...
2024-08-23 php开发问题
4

关于如何在 GoDaddy 服务器中使用 PHPMailer 设置 SMTP 的问题
Issue on how to setup SMTP using PHPMailer in GoDaddy server(关于如何在 GoDaddy 服务器中使用 PHPMailer 设置 SMTP 的问题)...
2024-08-23 php开发问题
17