是的,您可以使用 PhpUnit 和 Mockery 来模拟 PHP 静态方法!
案例:待测类Foo(Foo.php)使用ToBeMocked类的静态方法mockMe。
<?php
namespace Test;
use Test\ToBeMocked;
class Foo {
public static function bar(){
return 1 + ToBeMocked::mockMe();
}
}
ToBeMocked 类 (ToBeMocked.php)
<?php
namespace Test;
class ToBeMocked {
public static function mockMe(){
return 2;
}
}
PhpUnit 测试文件 (FooTest.php) 模拟静态方法(使用 Mockery):
<?php
namespace Test;
use Mockery;
use Mockery\Adapter\Phpunit\MockeryTestCase;
// IMPORTANT: extends MockeryTestCase, NOT EXTENDS TestCase
final class FooTest extends MockeryTestCase
{
protected $preserveGlobalState = FALSE; // Only use local info
protected $runTestInSeparateProcess = TRUE; // Run isolated
/**
* Test without mock: returns 3
*/
public function testDefault()
{
$expected = 3;
$this->assertEquals(
$expected,
Foo::bar()
);
}
/**
* Test with mock: returns 6
*/
public function testWithMock()
{
// Creating the mock for a static method
Mockery::mock(
// don't forget to prefix it with "overload:"
'overload:Geko\MVC\Models\Test\ToBeMocked',
// Method name and the value that it will be return
['mockMe' => 5]
);
$expected = 6;
$this->assertEquals(
$expected,
Foo::bar()
);
}
}
运行此测试:
$ ./vendor/phpunit/phpunit/phpunit -c testes/phpunit.xml --filter FooTest
PHPUnit 9.5.4 by Sebastian Bergmann and contributors.
Runtime: PHP 8.0.3
Configuration: testes/phpunit.xml
.. 2 / 2 (100%)
Time: 00:00.068, Memory: 10.00 MB
OK (2 tests, 3 assertions)