【问题标题】:How to test method with callable argument in PHPUnit如何在 PHPUnit 中使用可调用参数测试方法
【发布时间】:2018-05-28 12:37:14
【问题描述】:

类中有一些私有静态方法。像

class Some {
    …
    private static function getSome($x) {…}
    …
}

它被用作可从同一个“Some”类的其他公共方法中调用

$a = self::getSuperSome(
    [__CLASS__, 'getSome']
);

当我试图改变时

$actual = Some::getSuperSome(
    ['Some', 'getSome'] // Should be changed ?
);

PHPUnit 出错

TypeError: 传递给 App\Some::getSuperSome() 的参数 blah-blah 必须是可调用的,给定数组...' blah-blah

如何更改 PHPUnit SomeTest 类中的 args 名称以测试 getSuperSame?

【问题讨论】:

  • 单元测试用于测试公共接口而不是私有/受保护的方法。此外,您不应该一开始就使用静态方法。我们现在可以选择在 PHP 中命名函数。
  • @tereško 我想测试 public getSuperSome 方法。如果我将 getSome 的可见性更改为 public 我会收到相同的错误消息。
  • [__CLASS__, 'getSome'] 作为可调用对象是非常有效的(如果在正确的范围内完成),那么某处肯定存在其他问题。请考虑提供更多代码(例如this)
  • 请做考虑 tereško 的评论

标签: php unit-testing oop phpunit


【解决方案1】:

首先,您需要创建任何命名空间,例如namespace Testnamespace;。之后必须将访问修饰符更改为static public function getSome($x)。然后你可以在类声明下尝试下面的代码来实现你的输出。

call_user_func_array(__NAMESPACE__ .'\Some::getSome', array('Some','getSome'));

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-03-20
    • 1970-01-01
    • 2017-03-05
    • 2018-08-05
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多