简体   繁体   English

PHP 单元 - 模拟 Class

[英]PHP Unit - Mock Class

How to mock class method getResult() ?如何模拟 class 方法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);

PHPUnit will ignore mocking static methods: PHPUnit将忽略 mocking static 方法:

Please note that final, private, and static methods cannot be stubbed or mocked.请注意,final、private 和 static 方法不能被存根或模拟。 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.它们被 PHPUnit 的测试双重功能忽略并保留其原始行为,除了 static 方法将被抛出\PHPUnit\Framework\MockObject\BadMethodCallException exception.

https://phpunit.readthedocs.io/en/9.2/test-doubles.html?highlight=static#test-doubles 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.你不能用 PHPUnit 的phpunit-mock-objects库来做到这一点。 Seek to the alternative - Mockery :寻求替代方案 -嘲弄

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

$this->exampleClassMock
  ->shouldReceive('getResult')
  ->once()
  ->andReturn(true);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM