如何使用不存在的回调 class 作为参数测试函数

How to test function with nonexist callback class as parameter

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

示例:

UserClass { 
    userMethod() {
        return $data;
    }
}

MyClass {
    myFunction (callback ) {
        doingSomething();
        doingSomething();
        $data = call_user_function($callback);
        return doingSomethingWithData($data);
    }
}

问题是,这是 API,我无法将客户 class 实现为回调,因为不存在,但我需要测试该函数是否适用于预期数据。有没有可能如何使用 phpunit 测试我的功能?

非常感谢

只需传入 returns 预期结果的匿名函数即可,您可以预测其输出。确保它正确处理垃圾数据 out/edge 个案例。 您的测试可能看起来像这样:

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) {

}

这将确保您只能调用您的函数。