如何使用nonxist回调类作为参数测试函数

时间:2016-01-19 23:21:51

标签: php callback phpunit

我有以下问题。我为我们的网站做API,客户必须在我的函数中使用他的函数作为回调函数。

示例:

<html>
<script>
    function test() {
        alert('SHOULD BE FIRST');
    }
</script>

<script>
// Dean Edwards/Matthias Miller/John Resig

function init() {

// quit if this function has already been called
if (arguments.callee.done) return;

    alert("hello init");

// flag this function so we don't do the same thing twice
arguments.callee.done = true;

// kill the timer
if (_timer) clearInterval(_timer);

// do stuff
};

/* for Mozilla/Opera9 */
if (document.addEventListener) {
document.addEventListener("DOMContentLoaded", init, false);
}

/* for Internet Explorer */
/*@cc_on @*/
/*@if (@_win32)
document.write("<script id=__ie_onload defer src=javascript:void(0)><\/script>");
var script = document.getElementById("__ie_onload");
script.onreadystatechange = function() {
    if (this.readyState == "complete") {
    init(); // call the onload handler
    }
};
/*@end @*/

/* for Safari */
if (/WebKit/i.test(navigator.userAgent)) { // sniff
var _timer = setInterval(function() {
    if (/loaded|complete/.test(document.readyState)) {
    init(); // call the onload handler
    }
}, 10);
}

/* for other browsers */
window.onload = init;
</script>

<body onload="test();">

</body>

</html>
问题是,这是API,我不能实现客户类作为回调,因为不存在,但我需要测试该功能将与预期数据一起工作。有没有可能使用phpunit测试我的功能?

非常感谢

1 个答案:

答案 0 :(得分:2)

只需传入一个匿名函数,该函数返回预期结果即可预测输出的结果。确保它正确处理垃圾数据输出/边缘情况。 您的测试看起来像这样:

class MyClassTest extends PHPUnit_Framework_TestCase
{
    /**
     * @dataProvider myFunctionProvider
     */
    public function testMyFunction($callback, $expected)
    {
        $this->assertEquals(
            // Just as example you can create instance of class and call it.
            MyClass::MyFunction($callback),
            $expected
        );
    }

    public function myFunctionProvider()
    {
        return [
            [ function () { return 'a';}, 'a'],
            [ function () { return 'c';}, 'c'],
            [ function () { return 'b';}, 'b']
        ];
    }
}

作为旁注,请将您的代码更改为:

function MyFunc(callable $callback) {

}

确保你只能调用你的函数。

相关问题