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);
4

1 Answer 1

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);
Sign up to request clarification or add additional context in comments.

1 Comment

You cannot use phpunit-mock-objects with current versions of PHPUnit.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.