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

如何在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!

图片转代码服务由CSDN问答提供 功能建议

我对单元测试比较新,所以也许有人可以帮助我。 \ n

问题

在终端中执行PHP单元测试时出现以下错误消息:

 < 代码>致命错误:在123行的/path/to/file.php中调用未定义的函数Path \ to \ missing_function()
   
 
 

通常,我现在会 使用 getMock(originalClassName)函数创建一个虚拟对象,然后预定义应该为 missing_function()返回的内容,但遗憾的是该函数未被放置 在任何接口/类中,就像我到目前为止所测试的所有其他函数一样。

任何人都有想法吗? 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());
        }
    }
    
    打赏 评论

相关推荐 更多相似问题