sh1r3f's avatar

How to mock injected Request in constructor

I'm trying to write tests for a package I'm developing (Thus I can't make actual requests). and somewhere in the package I've a class that has the request injected to the constructor that it uses in all its method.

public function __construct(\Symfony\Component\HttpFoundation\Request $request, ...$otherArgs){
	$this->request = $request;
}

public function methodIwantToTest(){
$content = $this->request->getContent();
return $content;
}

What I want to do is simply mock that injected request and for example make the getContent function returns "test"... How can I go through this in my tests?

I'm using pestphp for testing and I tried this approach

    $this->app->instance(
        Request::class,
        Mockery::mock(Request::class, function ($mock) {
            $mock->shouldReceive('getContent')->andReturn('test');
        })
    );

but didn't work with me

any guidance would be very appreciated.

0 likes
2 replies
LaryAI's avatar
Level 58

You can use the makePartial method from Mockery to mock the Request class. This will allow you to mock the getContent method and return the value you want.

$mockRequest = Mockery::mock(Request::class);
$mockRequest->shouldReceive('getContent')->andReturn('test');

$this->app->instance(Request::class, $mockRequest->makePartial());

This should allow you to mock the Request class and return the value you want in your tests.

1 like
sh1r3f's avatar

@LaryAI Unfortunately it didn't work. Maybe the problem within my code? here's my test file.

beforeEach(function () {

    $mockRequest = Mockery::mock(Request::class);
    $mockRequest->shouldReceive('getContent')->andReturn('test');

    $this->app->instance(Request::class, $mockRequest->makePartial());
});

here is the class that I want to mock (Which is a 3rd party package and I just modified it now for testing)

    /**
     * Driver constructor.
     * @param Request $request
     * @param array $config
     * @param HttpInterface $http
     */
    final public function __construct(Request $request, array $config, HttpInterface $http)
    {
        dd($request->getContent());

        $this->http = $http;
        $this->config = Collection::make($config);
        $this->content = $request->getContent();
        $this->buildPayload($request);
    }

Response

composer test
"" // Class path:39

Please or to participate in this conversation.