php - 如何在 PHPUnit 中获取确定的调用方法的数量

标签 php unit-testing testing mocking phpunit

目前我正在使用字符串来指定我的测试失败的地方,如下所示:

In the first call to 'XY' method, the first parameter:

所以,想用phpunit获取通话次数。

简而言之,我想要一个基数而不是 first, second, third ...,但是给了 phpunit(更好)

public function testExample()
{
    $test = $this;

    $this->myClass
        ->expects($this->exactly(2))
        ->method('methodOne')
        ->withConsecutive(
            [
                $this->callback(function ($arg) use ($test) {
                    $part = 'In the first call to methodOne method, the first parameter: ';

                    $test->assertThat(
                        $arg,
                        $this->logicalAnd($this->equalTo('example1')),
                        $part . 'is not equal to "example1" '
                    );

                    return true;
                }),
            ],
            [
                $this->callback(function ($arg) use ($test) {
                    $part = 'In the first call to methodOne method, the first parameter: ';

                    $test->assertThat(
                        $arg,
                        $this->logicalAnd($this->equalTo('example2')),
                        $part . 'is not equal to "example2"'
                    );

                    return true;
                }),
            ]
        )
        ->will($this->returnSelf());
}

最佳答案

使用预言:

 class A {
    function abc($a, $b) {
        return ...;
    }
 }

    $a = $this->prophesize (A::class);
    $a->abc (1,2)->willReturn ("something");
    $A = $a->reveal ();

    $A->abc (1, 2);
    $A->abc (1, 2);
    $A->abc (1, 2);

这为您提供了通话次数:

    $calls = $a->findProphecyMethodCalls ("abc", new ArgumentsWildcard([new AnyValuesToken]));
    var_dump (count($calls));

您可以遍历所有调用以查看它们的参数:

    foreach ($calls as $call)
    {
        var_dump ($call->getArguments());
    }

关于php - 如何在 PHPUnit 中获取确定的调用方法的数量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45848314/

相关文章:

php - 使用 where 子句和 if 语句进行 MySQL 查询

php - 分页没有值(value)到第二页?

unit-testing - 在经济时代作为一个团体开始进行单元测试

ruby-on-rails - 如何测试复合 Rails 模型范围?

Java - JUnit 测试生成器

ruby-on-rails - Rails ActiveRecord 序列化方法在测试环境中不起作用

php - PHP 中的默认时区

php - Magento 2 Apache 随机 400 错误

javascript - Jasmine 中使用外部库进行单元测试

java - org.openqa.selenium.WebDriverException : chrome not reachable