php - 无法断言 PHPUnit 中的参数类型

标签 php unit-testing testing phpunit

断言:

$chain->expects($this->once())
   ->method('addMethodCall')
   ->with(
       'addOptionsProvider',
       array(
          $this->isInstanceOf('Symfony\Component\DependencyInjection\Reference'),
          $this->equalTo(7)
       )
   );

$chain 实际上是 Definition 的模拟对象,这是我要测试的代码:

$definition->addMethodCall(
    'addOptionsProvider',
    array(new Reference($id), $priority)
);

我刚开始使用 PHPUnit,所以我真的不知道我错过了什么。我发现断言论点真的很难理解。我已经包含了一个图像,其中包含断言和实际参数之间的视觉差异。

PHPUnit_Framework_ExpectationFailedException : Expectation failed for method name is equal to when invoked 1 time(s) Parameter 1 for invocation Symfony\Component\DependencyInjection\Definition::addMethodCall('addOptionsProvider', Array (...)) does not match expected value.

enter image description here

编辑:实际上,我最终得到了这个:

$chain->expects($this->once())
    ->method('addMethodCall')
    ->with(
        $this->identicalTo('addOptionsProvider'),
        $this->logicalAnd(
            $this->isType('array'),
            $this->arrayHasKey(0),
            $this->arrayHasKey(1)
        )
    );

但我不能“进入”数组值以进行进一步断言!

最佳答案

->with() 的方法签名与您预期的不同。

->with(string|PHPUnit_Framework_Constraint, ...)

这意味着您不能只向其中传递一个数组,因为 PHPUnit 不够“智能”,无法理解您的意思。

模拟这个的最简单方法应该是:

->with(
   'addOptionsProvider',
   array(
      new Reference(1),
      7
   )
)

因为它只会比较数组。

另一种模拟这个的方法(如果你需要对对象进行方法调用等等)是使用

->with($this->callback(function($arg)  { ... } ));

并在那里做出你的断言。

有关复杂示例,请参阅:mock atLeastOnce with concrete value, the rest not important

关于php - 无法断言 PHPUnit 中的参数类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13962206/

相关文章:

unit-testing - 有没有办法通过maven/ant运行nodeunit测试

c++ - 如何在 Visual Studio 中的 CppUnitTestFramework (C++) 中设置超时?

maven - 如何通过从 Web 界面单击来触发 Junit/Testng 测试运行

iOS - 在加载 View Controller 之前模拟 UserDefault

PHP - 每个选项卡的 session

javascript - 如何在datepicker函数中传递php参数

java - Spring - 使用模拟进行单元测试 - 如何在服务单元测试中模拟自定义收集器

java - 使用任何传递的参数模拟返回

php - 在 mysql 中存储回历日期的最佳方式?

apache - 记录错误日志的URL