Mock and inject static method in PHPUnit

Rate this post

I want to unit test the following function using PHPUnit.

use Requests;

class Some_Class{
    public function some_function_i_want_to_test() {
        $my_requests = [];

        // some code to create my_requests 

        $responses = Requests::request_multiple( $my_requests );
        return $responses;

How do I mock and inject a stub for Requests::request_multiple?

I started with:

private function mock_requests() {
    $requests_mock = $this->getMockBuilder( Requests::class )
    ->setMethods( [ 'request_multiple' ] )

    $requests_mock->method( 'request_multiple' )->willReturn( 'response body' );

but I am not sure how to mock a static method or how to inject it into my class.



You cannot inject something static because you are not using an instance to access the method.

A workaround for your case would be to build a wrapper class for that static call:

class RequestWrapper
    public function request_multiple($yourParam) {
        return Request::request_multiple($yourParam);

You can then inject an instance of this class in the method/class that you want to test and mock it when appropriate.

Leave a Reply

Your email address will not be published.

Back to top button