1

I have an issue returning correct behaviour when mocking specific object while writing tests in Symfony 5.

My method:

public function myTestFunction(TokenInterface $token)
    {
        $user = $token->getUser();
        if (!$user instanceof UserInterface) {
            return false;
         }

      ..... 
     }

I was trying in my tests like:

$this->token = $this->createMock(TokenInterface::class);
$this->token
     ->method('getUser')
     ->willReturn(UserInterface::class);

Result does not replicate the behaviour I want to accomplished based on the code I posted.

As I am defining $token as a stub, I am forced to describe every interaction with it, otherwise PHPUnit, will return null for every method call.

yaraw69
  • 43
  • 5

1 Answers1

1

In your ->willReturn call you should pass the real object instead of string of the class name. This is what I see wrong in your current code.

So you should create real User class which is an instance of the UserInterface and pass this object into ->willReturn($realUserObject).

I think it should help you.

  • Thank you for the answer @SzymonSzymkowiak . I guess something else is the problem as I tried with your proposition and still getting null. I will post another question. – yaraw69 Jul 08 '22 at 03:58
  • @yaraw69 you can try to use getMockBuilder, look here https://stackoverflow.com/questions/38363086/what-is-the-difference-between-createmock-and-getmockbuilder-in-phpunit – Szymon Szymkowiak Jul 08 '22 at 05:21
  • Tried with that. Still the same. Thanks for trying to help! Can you please check: https://stackoverflow.com/questions/72906473/symfony-testing-vote-gets-null-on-mock-tokeninterface to see my actual problem? Thanks @ SzymonSzymkowiak – yaraw69 Jul 08 '22 at 05:29