测试是否使用某些参数调用了该方法 [英] Test that method is called with some parameters, among others

查看:49
本文介绍了测试是否使用某些参数调用了该方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在用phpunit测试方法,并且出现以下情况:

I'm testing a method with phpunit and I have the following scenario:

  • 方法"setParameter"被称为未知次数
  • 'setParameter'方法使用不同种类的参数调用
  • 必须使用一组参数调用各种参数方法"setParameter".

我尝试过这种方式:

$mandatoryParameters = array('param1', 'param2', 'param3');
foreach ($mandatoryParameters as $parameter) {
    $class->expects($this->once())
        ->method('setParameter')
        ->with($parameter);
}

不幸的是,测试失败,因为在用这些参数调用方法之前,它也用其他参数调用了.我得到的错误是:

Unfortunately the test failed because before method is called with these parameters it is called with other parameters too. The error i get is:

Parameter 0 for invocation Namespace\Class::setParameter('random_param', 'random_value')
does not match expected value.
Failed asserting that two strings are equal.

推荐答案

尝试使用$this->at()方法.每次循环时,您都将覆盖模拟.

Try using the $this->at() method. You are overwriting your mock each time with your loop.

$mandatoryParameters = array('param1', 'param2', 'param3');
$a = 0;
foreach ($mandatoryParameters as $parameter) {
    $class->expects($this->at($a++);
        ->method('setParameter')
        ->with($parameter);
}

这会将您的模拟设置为期望setParameter被调用一定的次数,并且每次调用将使用不同的参数.您将需要知道哪个调用特定于您的参数,并相应地调整编号.如果调用不是连续的,则可以为每个参数设置一个索引.

This will set your mock to expect setParameter to be called a certain number of times and each call will be with a different parameter. You will need to know which call is the specific on for your parameters and adjust the number accordingly. If the calls are not sequential, you can set a key for which index each param.

$mandatoryParameters = array(2 =>'param1', 5 => 'param2', 6 => 'param3');

foreach ($mandatoryParameters as $index => $parameter) {
    $class->expects($this->at($index);
        ->method('setParameter')
        ->with($parameter);
}

索引是从零开始的,因此请记住从0开始而不是从1开始计数.

The index is zero based so remember to start your counting from 0 rather than 1.

http://phpunit.de/manual/current/en/phpunit-book.html#test-doubles.mock-objects.tables.matchers

这篇关于测试是否使用某些参数调用了该方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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