断言PHPUnit中的参数类型失败 [英] Fail in asserting about argument types in PHPUnit

查看:122
本文介绍了断言PHPUnit中的参数类型失败的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

断言:

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

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

$chain is actually a mock object of Definition, and this is the code I'd like to test:

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

我开始使用PHPUnit,所以我真的不知道我缺少什么.我发现关于论点的断言确实很难理解.我提供了一个图像,该图像具有断言和实际参数之间的视觉差异.

I'm beginning PHPUnit, so I really don't know what I'm missing. I'm finding asserting about arguments really hard to understand. I've included an image with the visual difference between the assertion and the actual parameters.

PHPUnit_Framework_ExpectationFailedException:期望失败 方法名称等于被调用1次 调用的参数1 Symfony \ Component \ DependencyInjection \ Definition :: addMethodCall('addOptionsProvider', 数组(...))与期望值不匹配.

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.

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

EDIT: actually, I ended up with this:

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

但是我不能进入"数组值以进行进一步的断言!

But I can't "go" into the array values for making further assertion!

推荐答案

->with()具有与您期望的方法签名不同的方法签名.

->with() has a different method signature than you expect it to have.

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

意味着您不能仅仅在其中传递数组,因为PHPUnit不够智能"以至于无法理解您的意思.

meaning that you can't just pass an array in there because PHPUnit isn't "smart" enough to figure out what you mean.

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

The easiest way to mock this should be:

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

因为它将只比较数组.

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

Another way to mock this (if you need to make method calls on objects and so on) is to use

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

并在那里声明.

有关一个复杂的示例,请参见: mock具有具体价值的atLeastOnce,其余的都不重要

For a complex example see: mock atLeastOnce with concrete value, the rest not important

这篇关于断言PHPUnit中的参数类型失败的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆