Phpunit 如何为静态方法编写PHP单元测试
我对PHP单元测试非常陌生。我正在尝试为以下函数创建单元测试:Phpunit 如何为静态方法编写PHP单元测试,phpunit,Phpunit,我对PHP单元测试非常陌生。我正在尝试为以下函数创建单元测试: $context = $args[0]; if (Subscriber::instance()->isSubscriber()) { $context['body_class'] .= ' ' . $this->bodyClass; } return $context; 若用户是订户,那个么在数组中添加类名是非常简单的。Subscriber是具有静态实例方法的类,该方
$context = $args[0];
if (Subscriber::instance()->isSubscriber()) {
$context['body_class'] .= ' ' . $this->bodyClass;
}
return $context;
若用户是订户,那个么在数组中添加类名是非常简单的。Subscriber是具有静态实例方法的类,该方法返回true或false
到目前为止,我已经写了这篇文章,但我不认为这是正确的:
$subscriber = $this->getMockBuilder(Subscriber::class)
->disableOriginalConstructor()
->setMethods(['isSubscriber'])
->getMock();
$subscriber->expects($this->once())
->method('isSubscriber')
->will($this->returnValue(true));
$this->assertInternalType('bool',$subscriber->isSubscriber());
任何帮助都将不胜感激。您可以测试(断言)静态方法,但不能在PHPunit中模拟或存根它们
从:
请注意,final、private和static方法不能被存根
或者嘲笑。PHPUnit的测试双重功能和
保留其原始行为,但将被删除的静态方法除外
替换为抛出
\PHPUnit\Framework\MockObject\BadMethodCallException异常
对于一个老问题来说,这是一个迟来的答案,但我认为它对某些人是有用的 是的,您可以使用与一起模拟PHP静态方法 案例:要测试的类Foo(
Foo.php
)使用类的静态方法mockMe
<?php
namespace Test;
use Test\ToBeMocked;
class Foo {
public static function bar(){
return 1 + ToBeMocked::mockMe();
}
}
PhpUnit测试文件(FooTest.php
)包含静态方法的mock(使用mockry):
祝你好运
<?php
namespace Test;
class ToBeMocked {
public static function mockMe(){
return 2;
}
}
<?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)