framework: Test using `$this->mock(Request::class)` always returning empty GET request

  • Laravel Version: 8.48.1
  • PHP Version: 7.4.13

Description:

In a Unit test for a Controller I mocked the request using the following;

$request = $this->mock(Request::class, static function (MockInterface $mock) use ($valid): void {
    $mock->shouldReceive('validated')->once()->andReturn($valid);
});

Which gave a valid result until updating Laravel from 8.47 to 8.48.

It seems that the introduction of the singletonInstance in the commit bind mock instances as singletons so they are not overwritten and the use of that in the mock(), partialMock() and spy() methods of the InteractsWithContainer trait. This seems to mean that an empty GET request is always used.

I have been able to resolve my failing tests by going back to the longer version of the code to mock an object, as found in the documentation.

$request = $this->instance(
    Request::class,
    Mockery::mock(Request::class, static function (MockInterface $mock) use ($valid): void {
        $mock->shouldReceive('validated')->once()->andReturn($valid);
    })
);

Steps To Reproduce:

$request = $this->mock(Request::class, static function (MockInterface $mock) use ($valid): void {
    $mock->shouldReceive('validated')->once()->andReturn($valid);
});

returns different $request compared to

$request = $this->instance(
    Request::class,
    Mockery::mock(Request::class, static function (MockInterface $mock) use ($valid): void {
        $mock->shouldReceive('validated')->once()->andReturn($valid);
    })
);

About this issue

  • Original URL
  • State: closed
  • Created 3 years ago
  • Reactions: 4
  • Comments: 23 (22 by maintainers)

Commits related to this issue

Most upvoted comments

@mpyw I’m sorry but I still believe you’re not correctly using that. Please try a support channel.

@mpyw you’re misusing that it seems. You need to provide a callback with the assertions so they’re bound to the container: https://laravel.com/docs/8.x/mocking#mocking-objects

@Nacoma that is actually an entirely different bug you have solved. I will write a test case.