Phpunit mock static method

PHPUnit Mock Static Method

Mocking a static method in PHPUnit can be done using the getMockForStaticMethod method provided by the PHPUnit framework. This allows us to create a mock object for a class and mock its static methods.

Example:

Let’s say we have a static method getFullName inside a class named User, which concatenates first name and last name and returns the full name. We want to mock this static method during our unit testing.


class User {
  public static function getFullName($firstName, $lastName) {
    return $firstName . ' ' . $lastName;
  }
}

// Unit test for mocking the static method
public function testGetFullName() {
  $mock = $this->getMockBuilder(User::class)
               ->setMethods(['getFullName'])
               ->getMock();

  $mock::expects($this->any())
       ->method('getFullName')
       ->willReturn('John Doe');

  $this->assertEquals('John Doe', $mock::getFullName('John', 'Doe'));
}
  

In the above example, we create a mock object of the User class using the getMockBuilder method. We specify the methods to be mocked using the setMethods method. Here, we only want to mock the getFullName method.

Next, we set an expectation on the getFullName method using the expects and method methods. We use the willReturn method to specify the value that should be returned when the static method is called.

Finally, we call the static method getFullName on the mock object and assert that it returns the expected value.

This way, we have successfully mocked the static method of the User class and tested our code using PHPUnit.

Leave a comment