phpunit icon indicating copy to clipboard operation
phpunit copied to clipboard

Feature similar to withConsecutive(), but without checking order

Open dbrekelmans opened this issue 6 years ago • 65 comments

In the docs we find this example for withConsecutive():

<?php
use PHPUnit\Framework\TestCase;

class FooTest extends TestCase
{
    public function testFunctionCalledTwoTimesWithSpecificArguments()
    {
        $mock = $this->getMockBuilder(stdClass::class)
                     ->setMethods(['set'])
                     ->getMock();

        $mock->expects($this->exactly(2))
             ->method('set')
             ->withConsecutive(
                 [$this->equalTo('foo'), $this->greaterThan(0)],
                 [$this->equalTo('bar'), $this->greaterThan(0)]
             );

        $mock->set('foo', 21);
        $mock->set('bar', 48);
    }
}

If your class calls method set with parameter foo first and with parameter bar second, the test will pass. However, if you call it with bar first and foo second the test will fail. This leads to brittle tests (as is mentioned in a note under the at() docs).

It would be lovely to have a way to check method 'foo' is called exactly twice. Once with parameter 'x' and once with parameter 'y', without checking the order.

A concrete example is testing that certain events are dispatched when it doesn't matter in what order they are dispatched (of course sometimes you do care about the order and in that case you can use withConsecutive()).

dbrekelmans avatar Jan 24 '20 09:01 dbrekelmans

@dbrekelmans @jaapio Sorry for dropping the ball on this. Are you able to send a pull request with an implementation for this in time for PHPUnit 10 (February 5, 2021)?

sebastianbergmann avatar Dec 28 '20 06:12 sebastianbergmann

No sorry, I had to spend more time on my own projects. So I didn't have the time to design something for this.

Unless I find a way to focus a longer period on the mocks. I don't think I will be able to provide a patch for this.

jaapio avatar Dec 28 '20 07:12 jaapio

Not likely within the timeframe. I can look into it, but I don't know how much time I'll have to work on this and I've never worked on the PHPUnit codebase before so it'll take more time to figure out a solution.

dbrekelmans avatar Dec 28 '20 07:12 dbrekelmans

Thank you for getting back to me so quickly. I'll see what I can do.

sebastianbergmann avatar Dec 28 '20 07:12 sebastianbergmann

Any update on this? Thanks!

sebastianbergmann avatar Apr 14 '21 10:04 sebastianbergmann

Not from my side. The best thing to do from my point of view would be to remove phpunit internal mocking system. This is really a project on its own. When I first dived into this it seemed to be feasible within a short period of time to resolve this problem. But the more I looked at it, the more I realized that this would be way too much work for me.

I can recommend you to re-evaluate whether you want to keep mocks as part of phpunit. Knowing that phpunit mocks do have their limits and quirks. But also that prophecy and mockery are a very good replacement. Which both fixed the problem as described.

To be honest I try to avoid the problem right now or use the earlier mentioned mock frameworks.

jaapio avatar Apr 14 '21 16:04 jaapio

My workaround for this must-have feature was a willReturnCallback() with a "static variable" that the caller manages and that can change the behavior of the callback method in runtime if needed.

mxr576 avatar Apr 19 '21 14:04 mxr576

As of right now, I do not think that we should create a replacement for withConsecutive(). Some context is provided here.

sebastianbergmann avatar Apr 23 '21 07:04 sebastianbergmann

Thanks @sebastianbergmann for the blogpost. I agree with your vision. Although in legacy projects you do not always have the time/capability/motivation to implement this correctly, it is not the responsibility of phpunit to fix this problem :)

dbrekelmans avatar Apr 29 '21 08:04 dbrekelmans

Where does this leave us on setting up expectations on a method that should return different values based on the arguments it's called with? Previously this was doable (albeit in a brittle way) via at(), but that's not longer possible because of https://github.com/sebastianbergmann/phpunit/issues/4298. Then the suggested solution was to use withConsecutive(), but that's also not going to be possible (at least in a way that isn't to be removed) because of https://github.com/sebastianbergmann/phpunit/issues/4026#issuecomment-825453794 and https://github.com/sebastianbergmann/phpunit/issues/4565.

Having a feature like this would be a good solution. For example, say you're using doctrine and you do ->getRepository() twice, how would you go about returning the related repository mock based on the passed entity argument? Needing to use a callback and manually keep track of which to return is kinda meh.

FWIW, mockery takes the expectation's arguments into consideration when determining which one to use. I.e. this is valid, which is a pretty clean way to go about it.

$this
    ->em
    ->shouldReceive('getRepository')
    ->with(User::class)
    ->andReturn($userRepository)
    ->once();

$this
    ->em
    ->shouldReceive('getRepository')
    ->with(Article::class)
    ->andReturn($articleRepository)
    ->once();

Has it been considered doing something similar to that?

Blacksmoke16 avatar Jul 08 '21 04:07 Blacksmoke16

The problem is not that nobody want's this feature. But nobody has time to implement it. There are alternatives like mockery and prophecy which are working perfectly with phpunit. However, I'm absolutely sure that any contribution regarding this ticket will be accepted.

For me this was the mean reason to choose to spend my time on other more important projects.

jaapio avatar Jul 11 '21 10:07 jaapio

I'm late to the party but just saw this was deprecated when upgrading from 9.5 to 9.6. I guess I'm confused why something would be deprecated without a replacement if a replacement is desired. That's like saying I want to bake something but don't know how so I guess I'll remove the oven. That's irrational thinking.

I don't believe saying things like "use mockery or prophecy" are valid solutions. Some of us don't want to install tons of bloated additional libraries to do a simple thing that has been available for 16+ years.

It's a shame that one or two people complaining about not understanding or remembering how withConsecutive() works can get such a useful feature removed for the entire community. 😞

bizurkur avatar Feb 03 '23 16:02 bizurkur

Please take in mind that phpunit was build by a single person, lucky it's maintained by a group of people nowadays.Direction of the project is always chosen by the maintainers. Not by me or any other community members.

Your opinion on this topic might be different, that's perfectly fine. But you cannot force the maintainers of a project in a direction. They chose wisely based on input and their own thoughts.

Phpunit drops support for methods every release, which moves the project in a certain direction. Given the fact that the project exists for so many years, I think we can only be thankful that this group of people are spending there time and passion on this lovely project.

jaapio avatar Feb 03 '23 17:02 jaapio

The blog post you linked is dead @sebastianbergmann

BafS avatar Feb 03 '23 18:02 BafS

https://thephp.cc/articles/do-not-mock-what-you-do-not-own

EDIT: Thanks for all the downvotes. I just wanted to post the new link to Sebastian's article since the old link from above was broken. I personally also don't agree with this decission.

LordSimal avatar Feb 03 '23 18:02 LordSimal

Do you understand that I feel a bit offended by the way you are talking about my try to improve the mocking framework? I have spent multiple days to create an issue, discus what is needed, crafted a poc, and I did fail. My final conclusion was that I preferred another solution rather than spending more time on this method.

The final decision to remove the method was made months after I opened the issue.

Please be careful with the way you position others in your opinion. I think nobody here was trying to remove any use case. We are all trying to improve the project with contributions.

jaapio avatar Feb 03 '23 19:02 jaapio

For anyone reading this in 2023, you can solve the issue with willReturnCallback() and match:

$mock->expects($this->exactly(2))
    ->method('set')
    ->willReturnCallback(fn (string $property, int $value) => match (true) {
        $property === 'foo' && $value > 0,
        $property === 'bar' && $value > 0 => $mock->$property = $value,
        default => throw new LogicException()
    });

I'm writing a package to help migrate from Prophecy, but most of the time match is good enough.

olvlvl avatar Feb 05 '23 13:02 olvlvl

This is my temporary solution to still support withConsecutive():

<?php

declare(strict_types=1);

use PHPUnit\Framework\Constraint\Callback;
use PHPUnit\Framework\Constraint\Constraint;

use function array_column;
use function count;

trait PHPUnitHelper
{
    /**
     * @param array<mixed> $firstCallArguments
     * @param array<mixed> ...$consecutiveCallsArguments
     *
     * @return iterable<Callback<mixed>>
     */
    public static function withConsecutive(array $firstCallArguments, array ...$consecutiveCallsArguments): iterable
    {
        foreach ($consecutiveCallsArguments as $consecutiveCallArguments) {
            self::assertSameSize($firstCallArguments, $consecutiveCallArguments, 'Each expected arguments list need to have the same size.');
        }

        $allConsecutiveCallsArguments = [$firstCallArguments, ...$consecutiveCallsArguments];

        $numberOfArguments = count($firstCallArguments);
        $argumentList      = [];
        for ($argumentPosition = 0; $argumentPosition < $numberOfArguments; $argumentPosition++) {
            $argumentList[$argumentPosition] = array_column($allConsecutiveCallsArguments, $argumentPosition);
        }

        $mockedMethodCall = 0;
        $callbackCall     = 0;
        foreach ($argumentList as $index => $argument) {
            yield new Callback(
                static function (mixed $actualArgument) use ($argumentList, &$mockedMethodCall, &$callbackCall, $index, $numberOfArguments): bool {
                    $expected = $argumentList[$index][$mockedMethodCall] ?? null;

                    $callbackCall++;
                    $mockedMethodCall = (int) ($callbackCall / $numberOfArguments);

                    if ($expected instanceof Constraint) {
                        self::assertThat($actualArgument, $expected);
                    } else {
                        self::assertEquals($expected, $actualArgument);
                    }

                    return true;
                },
            );
        }
    }
}

class Test extends TestCase
{

    public function testWithConsecutive(): void
    {
        // PHPUnit < 10
        $mock->withConsecutive(
            ['arg1_1', 'arg1_2'],
            ['arg2_1', 'arg2_2'],
        );

        // Using the trait
        $mock->with(
            ...self::withConsecutive(
                ['arg1_1', 'arg1_2'],
                ['arg2_1', 'arg2_2'],
            )
        );
    }
}




dragosprotung avatar Feb 05 '23 18:02 dragosprotung

Is there some additional explanation aside https://github.com/sebastianbergmann/phpunit/issues/4026#issuecomment-825453794? It goes against https://github.com/sebastianbergmann/phpunit/issues/4255#issuecomment-636422439 And I don't understand what does "do not mock what you don't own" mantra has to do with removal of this feature. I am mocking my own methods and now I cannot easily write call assertions.

ostrolucky avatar Feb 11 '23 16:02 ostrolucky

I'm also doing exactly the same as @ostrolucky (mocking just my own services) to test necessary use cases. I would love to see a viable replacement for this.

tarlepp avatar Feb 11 '23 16:02 tarlepp