0

How to mock class method getResult() ?

use App\ExampleClass;


$res = ExampleClass::getResult();

What I tried so far, and it didn't work:

$this->exampleClass = $this->getMockBuilder('App\ExampleClass')
    ->disableOriginalConstructor()
    ->getMock();


$this->exampleClass->expects($this->once())
    ->method('getResult')
    ->willReturn(true);
Klark
  • 423
  • 6
  • 16
  • Mocking static methods seems to have been possible but also seems to have been removed, https://stackoverflow.com/questions/2357001/phpunit-mock-objects-and-static-methods and https://github.com/sebastianbergmann/phpunit-documentation/issues/77 give more info. – Nigel Ren Jul 06 '20 at 10:34
  • Mocking static methods is not supported: https://phpunit.readthedocs.io/en/9.2/test-doubles.html "Please note that final, private, and static methods cannot be stubbed or mocked. They are ignored by PHPUnit’s test double functionality and retain their original behavior except for static methods that will be replaced by a method throwing a \PHPUnit\Framework\MockObject\BadMethodCallException exception." – Philip Weinke Jul 06 '20 at 11:48
  • It is not working... How? – Lajos Arpad Jul 06 '20 at 12:12
  • this worked https://stackoverflow.com/a/62757723/7594704 – Klark Jul 06 '20 at 15:29

1 Answers1

1

PHPUnit will ignore mocking static methods:

Please note that final, private, and static methods cannot be stubbed or mocked. They are ignored by PHPUnit’s test double functionality and retain their original behavior except for static methods that will be replaced by a method throwing a \PHPUnit\Framework\MockObject\BadMethodCallException exception.

https://phpunit.readthedocs.io/en/9.2/test-doubles.html?highlight=static#test-doubles

You can't do it with PHPUnit’s phpunit-mock-objects library. Seek to the alternative - Mockery:

$this->exampleClassMock = \Mockery::mock('overload:App\ExampleClass');

$this->exampleClassMock
  ->shouldReceive('getResult')
  ->once()
  ->andReturn(true);
t_dom93
  • 10,226
  • 1
  • 52
  • 38