dsjk3214 2014-06-04 06: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 10: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());
        }
    }
    

    展开全部

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
编辑
预览

报告相同问题?

手机看
程序员都在用的中文IT技术交流社区

程序员都在用的中文IT技术交流社区

专业的中文 IT 技术社区,与千万技术人共成长

专业的中文 IT 技术社区,与千万技术人共成长

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

客服 返回
顶部