![](/img/trans.png)
[英]How can I test a single void method inside a class with PHPUnit?
[英]How can I test that a method is private using PHPUnit
使用PHPUnit,我想测试无法使用__construct [ new Class(); ]
实例化一个类__construct [ new Class(); ]
__construct [ new Class(); ]
方法以及无法克隆,唤醒等。
基本上,它是一个Singleton类,并且__construct
, __clone
和__wakeup
方法设置为private,以确保它保持为Singleton。
但是我该如何测试呢?
您可以通过尝试从单例实例化新对象来捕获引发的异常来实现此目的。
尝试以下方法(PHP 7):
class Single
{
private function __construct() {}
}
class SingleTest extends \PHPUnit_Framework_TestCase
{
function testCannotCallConstructor()
{
try {
$single = new Single();
$this->fail('Should never be called!');
} catch (\Throwable $e) {
$this->assertNotEmpty($e->getMessage());
}
//alternative:
$this->expectException(\Error::class);
$single = new Single();
}
}
按照设计,单元测试通常检查行为,而不是接口(方法签名是接口的一部分)。
但是,如果您确实需要,可以使用Reflection API。 检查类hasMethod()
和此方法isPrivate()
。
在PHP7环境中,您可以使用John Joseph提出的try/catch
解决方案,但我建议仅拦截Error
异常( Throwable
涵盖所有可能的错误,不仅限于可见性违规)。 另外,PHPUnit还具有@expectedException
批注,它比手动try/catch
更好。
所有这些都运行良好。
function testCannotCallConstructor()
{
try {
$log = new Log();
$this->fail('Should never be called!');
} catch (\Throwable $e) {
$this->assertNotEmpty($e->getMessage());
}
//alternative:
$this->expectException(\Error::class);
$log = new Log();
}
public function testConstructPrivate(){
$method = new \ReflectionMethod('\\Core\\Log', '__construct');
$result = $method->isPrivate();
$this->assertTrue( $result, "Log __construct is not private. Singleton not guaranteed.");
}
非常感谢你。 我认为我更喜欢的是ExpectException方法。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.