服务器之家:专注于服务器技术及软件下载分享
分类导航

PHP教程|ASP.NET教程|JAVA教程|ASP教程|

服务器之家 - 编程语言 - PHP教程 - PHPUnit测试私有属性和方法功能示例

PHPUnit测试私有属性和方法功能示例

2019-09-25 13:45哎!无悔 PHP教程

这篇文章主要介绍了PHPUnit测试私有属性和方法功能,结合实例形式较为详细的分析了使用PHPUnit针对私有属性和方法进行测试的相关操作技巧与注意事项,需要的朋友可以参考下

本文实例讲述了PHPUnit测试私有属性和方法功能。分享给大家供大家参考,具体如下:

一、测试类中的私有方法:

class Sample
{
  private $a = 0;
  private function run()
  {
    echo $a;
  }
}

上面只是简单的写了一个类包含,一个私有变量和一个私有方法。对于protected和private方法,由于无法像是用public方法一样直接调用,所以在使用phpunit进行单测的时候,多有不便,特别是当一个类中,对外只提供少量接口,内部使用了大量private方法的情况。

对于protected方法,建议使用继承的方式进行测试,在此就不再赘述。而对于private方法的测试,建议使用php的反射机制来进行。话不多说,上代码:

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;
}

那么,测试代码可以改为:

$method->invokeArgs(new Sample(), array(1, 2));
//array中依次写入要传的参数。执行结果返回3

【注意】:利用反射的方法测试私有方法虽好,但setAccessible函数是php5.3.2版本以后才支持的(>=5.3.2)

二、私有属性的get/set

说完了私有方法,再来看看私有属性,依旧拿Sample类作为例子,想要获取或设置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程序设计有所帮助。

延伸 · 阅读

精彩推荐
  • PHP教程thinkphp5使用无限极分类

    thinkphp5使用无限极分类

    这篇文章主要为大家详细介绍了thinkphp5使用无限极分类,具有一定的参考价值,感兴趣的小伙伴们可以参考一下...

    tiramisuer80234982019-06-12
  • PHP教程php往mysql中批量插入数据实例教程

    php往mysql中批量插入数据实例教程

    这篇文章主要给大家介绍了关于php往mysql中批量插入数据的相关资料,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面来一起看看吧...

    nemo1402019-07-16
  • PHP教程PHP让网站移动访问更加友好方法

    PHP让网站移动访问更加友好方法

    在本文里我们给大家整理了关于PHP让网站移动访问更加友好的相关实例代码以及相关知识点,有需要的朋友们学习下。...

    laozhang2952019-06-15
  • PHP教程Laravel中为什么不使用blpop取队列详析

    Laravel中为什么不使用blpop取队列详析

    这篇文章主要给大家介绍了关于Laravel中为什么不使用blpop取队列的相关资料,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧 ...

    深 呼吸2942019-09-17
  • PHP教程tp5框架使用composer实现日志记录功能示例

    tp5框架使用composer实现日志记录功能示例

    这篇文章主要介绍了tp5框架使用composer实现日志记录功能,结合实例形式分析了thinkPHP5框架composer安装及日志记录相关操作技巧,需要的朋友可以参考下...

    TBHacker4982019-07-04
  • PHP教程PHP多个图片压缩成ZIP的方法

    PHP多个图片压缩成ZIP的方法

    这篇文章主要为大家详细介绍了PHP多个图片压缩成ZIP的方法,可将多个文件压缩成一个zip压缩包,具有一定的参考价值,感兴趣的小伙伴们可以参考一下 ...

    lijiao2432019-09-18
  • PHP教程PHP命名空间与自动加载机制的基础介绍

    PHP命名空间与自动加载机制的基础介绍

    这篇文章主要给大家介绍了关于PHP命名空间与自动加载机制的相关资料,文中通过示例代码介绍的非常详细,对大家学习或者使用PHP具有一定的参考学习价值,需要的朋友们下面来一起学习学习吧...

    woider1132019-08-28
  • PHP教程php判断电子邮件是否正确方法

    php判断电子邮件是否正确方法

    在本篇内容里小编给大家整理了一篇关于php判断电子邮件是否正确方法,需要的朋友们参考下。...

    laozhang1942019-07-26