dsjk3214 2014-06-04 14:22
浏览 41
已采纳

如何在PHP单元测试中处理对未定义函数的调用

I am relatively new to unit testing, so maybe someone can help me out here.

Problem

The following error message appears when executing the PHP unit test in the terminal:

Fatal error: Call to undefined function Path\to\missing_function() in /path/to/file.php on line 123

Normally, I would now create a dummy object using the getMock(originalClassName) function and then predefine what should be returned for missing_function() but sadly the function is not placed in any interface/class like all other functions I tested up to now.

Anyone got an idea here? Cheerio!

  • 写回答

1条回答 默认 最新

  • dongruo4601 2014-06-04 18:29
    关注

    Generally speaking, you would just include the file with the function and have it get executed. Then you just make sure that after your code was executed, what was supposed to happen happens. You are more concerned with the outcome of the code that you are testing rather than the process of how your code is executed.

    Though, if you need to mock a function there is a way using namespaces (need PHP 5.3+). In your test file, you can place a "mock" function that is in the same namespace as your code. When the function gets called php looks in the current namespace first and will find your replacement function. In the normal running of your code, it will proceed to the global namespace to call your function.

    So you code would end up like this:

    Your class:

    namespace Foo;
    
    class SUT {
        public function bar() {
            return baz();
        }
    }
    

    Your test:

    namespace Foo;
    
    function bar() {
        return 'boz';
    }
    
    class SUTTest extends PHPUnit_Framework_TestCase {
        public function testBar() {
            $sut = new SUT();
    
            $this->assertEquals('boz', $sut->bar());
        }
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥20 腾讯企业邮箱邮件可以恢复么
  • ¥15 有人知道怎么将自己的迁移策略布到edgecloudsim上使用吗?
  • ¥15 错误 LNK2001 无法解析的外部符号
  • ¥50 安装pyaudiokits失败
  • ¥15 计组这些题应该咋做呀
  • ¥60 更换迈创SOL6M4AE卡的时候,驱动要重新装才能使用,怎么解决?
  • ¥15 让node服务器有自动加载文件的功能
  • ¥15 jmeter脚本回放有的是对的有的是错的
  • ¥15 r语言蛋白组学相关问题
  • ¥15 Python时间序列如何拟合疏系数模型