本文将详细介绍如何使用PHPUnit对类的私有属性和私有方法进行单元测试,并提供具体的代码示例供参考。
测试类中的私有方法
一、测试类中的私有方法
class Sample
{
private $a = 0;
private function run()
{
echo $a;
}
}
上述代码仅展示了一个包含私有变量和私有方法的简单类。对于protected和private修饰的方法,由于无法像public方法那样直接实例化调用,在进行PHPUnit单元测试时往往面临不便。特别是当类对外只暴露少量接口,而内部依赖大量private方法实现逻辑时,测试难度会增加。
对于protected方法,通常建议通过继承子类的方式进行测试,此处不再赘述。针对private方法的测试,推荐使用PHP的反射机制(Reflection API)。以下是具体实现代码:
class testSample()
{
$method = new ReflectionMethod('Sample', 'run');
$method->setAccessible(true); //将run方法从private变成类似于public的权限
$method->invoke(new Sample()); //调用run方法
}
如果待测试的run方法是静态的,例如:
private static function run()
{
echo 'run is a private static function';
}
那么调用invoke函数的方式需调整为:
$method->invoke(null); //只有静态方法可以不必传类的实例化
如果run方法还需要接收参数,例如:
private function run($x, $y)
{
return $x + $y;
}
则测试代码应修改为使用invokeArgs传递参数数组:
$method->invokeArgs(new Sample(), array(1, 2));
//array中依次写入要传的参数。执行结果返回3
【注意】:利用反射方法测试私有方法虽然便捷,但需注意版本兼容性。setAccessible函数仅在PHP 5.3.2及以上版本(>=5.3.2)中可用。
私有属性的get/set操作
二、私有属性的get/set操作
了解了私有方法的测试后,接下来看私有属性。仍以Sample类为例,若要获取或设置私有属性$a的值,可采用如下反射方式:
public function testPrivateProperty()
{
$reflectedClass = new ReflectionClass('Sample');
$reflectedProperty = $reflectedClass->getProperty('a');
$reflectedProperty->setAccessible(true);
$reflectedProperty->getValue(); //获取$a的值
$reflectedProperty->setValue(123); //给$a赋值:$a = 123;
}
上述反射方法同样适用于静态属性的读写操作。
至此,测试私有方法或属性的流程已清晰明了。
附:PHPunit 测试私有方法(英文原文参考)
This article is part of a series on testing untestable code:
- Testing private methods
- Testing code that uses singletons
- Stubbing static methods
- Stubbing hard-coded dependencies
No, not those privates. If you need help with those, this book might help.
One question I get over and over again when talking about Unit Testing is this:
"How do I test the private attributes and methods of my objects?"
Lets assume we have a class Foo:
<?php
class Foo
{
private $bar = 'baz';
public function doSomething()
{
return $this->bar = $this->doSomethingPrivate();
}
private function doSomethingPrivate()
{
return 'blah';
}
}
?>
Before we explore how protected and private attributes and methods can be tested directly, lets have a look at how they can be tested indirectly.
The following test calls the testDoSomething() method which in turn calls thedoSomethingPrivate() method:
<?php
class FooTest extends PHPUnit_Framework_TestCase
{
/**
* @covers Foo::doSomething
* @covers Foo::doSomethingPrivate
*/
public function testDoSomething()
{
$foo = new Foo;
$this->assertEquals('blah', $foo->doSomething());
}
}
?>
The test above assumes that testDoSomething() only works correctly whentestDoSomethingPrivate() works correctly. This means that we have indirectly testedtestDoSomethingPrivate(). The problem with this approach is that when the test fails we do not know directly where the root cause for the failure is. It could be in eithertestDoSomething() or testDoSomethingPrivate(). This makes the test less valuable.
PHPUnit supports reading protected and private attributes through thePHPUnit_Framework_Assert::readAttribute() method. Convenience wrappers such asPHPUnit_Framework_TestCase::assertAttributeEquals() exist to express assertions onprotected and private attributes:
<?php
class FooTest extends PHPUnit_Framework_TestCase
{
public function testPrivateAttribute()
{
$this->assertAttributeEquals(
'baz', /* expected value */
'bar', /* attribute name */
new Foo /* object */
);
}
}
?>
PHP 5.3.2 introduces the ReflectionMethod::setAccessible() method to allow the invocation of protected and private methods through the Reflection API:
<?php
class FooTest extends PHPUnit_Framework_TestCase
{
/**
* @covers Foo::doSomethingPrivate
*/
public function testPrivateMethod()
{
$method = new ReflectionMethod(
'Foo', 'doSomethingPrivate'
);
$method->setAccessible(TRUE);
$this->assertEquals(
'blah', $method->invoke(new Foo)
);
}
}
?>
In the test above we directly test testDoSomethingPrivate(). When it fails we immediately know where to look for the root cause.
I agree with Dave Thomas and Andy Hunt, who write in their book "Pragmatic Unit Testing":
"In general, you don't want to break any encapsulation for the sake of testing (or as Mom used to say, "don't expose your privates!"). Most of the time, you should be able to test a class by exercising its public methods. If there is significant functionality that is hidden behind private or protected access, that might be a warning sign that there's another class in there struggling to get out."
So: Just because the testing of protected and private attributes and methods is possible does not mean that this is a "good thing".
参考文献:
http://php.net/manual/en/class.reflectionmethod.php
希望本文所述对大家PHP程序设计有所帮助。