jjoselon
jjoselon

Reputation: 2811

How to get number of a determined called to method in PHPUnit

Currently I'm using strings to specifies where my test fails, like this:

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

so, want to get the number of call with phpunit.

In short, I want a cardinal number instead of first, second, third ..., but given for phpunit (better)

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

Upvotes: 0

Views: 379

Answers (1)

akond
akond

Reputation: 16035

Using prophecy:

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

This gives you the number of calls:

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

You can loop through all the calls to see what their arguments were:

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

Upvotes: 1

Related Questions