如何在PHPUnit

时间:2017-08-23 19:57:16

标签: php unit-testing testing mocking phpunit

目前,我使用字符串来指定测试失败的位置,如下所示:

  

第一次打电话给' XY'方法,第一个参数:

所以,想用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());
}

1 个答案:

答案 0 :(得分:1)

使用预言:

 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());
    }