当前位置: 首页 > 编程文章 >

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

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

作者:江知时间:2025-01-12 16:23:23浏览:618

本文介绍在PHPUnit中测试类私有属性和方法的技巧。通过PHP反射机制ReflectionMethod,可以绕过访问限制直接调用private或protected方法,并支持静态方法及参数传递。同时演示了使用ReflectionClass读取和设置私有属性的方法,帮助开发者解决内部逻辑难以单测的问题。

本文目录展开

本文将详细介绍如何使用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程序设计有所帮助。

上一篇
PHP结合Redis实现悲观锁:从原理到最佳实践

本文介绍基于PHP和Redis的悲观锁实现机制。通过对比乐观锁与悲观锁,分析任务分发系统中的并发问题,并展示使用setnx、incr及set命令三种方式的代码实现,重点讲解如何利用Redis原子操作防止死锁及版本兼容性注意事项。

下一篇
PHP DateTime类解决1970年前及2038年后时间戳转换问题

在32位系统中,传统时间函数常因范围限制无法正确处理1970年之前或2038年之后的时间。PHP 5.2及以上版本提供的DateTime类能有效解决此问题。通过实例化DateTime对象并配合setTimezone设置时区,可实现Unix时间戳与日期字符串的双向转换,确保跨年代时间的准确计算。

相关文章

更多
PHP单元测试框架PHPUnit用法详解

本文介绍如何在PHP项目中通过Composer安装并配置PHPUnit及Monolog日志组件。内容涵盖单元测试的核心概念、基础测试类的创建与执行、断言方法的使用,以及利用--skeleton参数自动生成测试骨架的高级技巧,帮助开发者提升代码健壮性并降低维护成本。

2025.10.18 714
PHP 7.1+ PHPUnit 单元测试配置与使用指南

本文详细介绍如何在 PHP 7.1 及以上版本中配置和使用 PHPUnit 进行单元测试。内容涵盖通过 Composer 或 Phar 文件全局安装 PHPUnit,创建 phpunit.xml 配置文件,以及在 PhpStorm 中设置 PHPUinit 路径和 Include Path。同时演示了测试类的编写规范(继承 TestCase、public 方法、断言使用)以及通过 IDE 和命令行执行单个文件或全局单元测试的具体操作。

2025.04.10 529
ThinkPHP5集成PHPUnit进行单元测试详解

本文介绍在ThinkPHP5项目中集成PHPUnit进行单元测试的方法。相比官方think-testing组件模拟HTTP请求的方式,PHPUnit直接调用代码对象进行测试,更加灵活且符合标准规范。通过Composer安装PHPUnit后,可在tests目录下创建测试类,继承TestCase并编写以test开头的方法,利用断言验证逻辑正确性,从而提升代码健壮性并降低维护成本。

2025.11.30 508
PHP单元测试PHPUnit简单用法示例

本文介绍在Windows环境下使用PHPUnit进行PHP单元测试的基本流程。通过下载对应版本的phar文件并配置环境变量完成安装,随后编写被测类与测试类,利用assertEquals等断言方法验证代码逻辑,最终通过命令行运行测试脚本查看结果。

2025.05.02 302
PHP单元测试PHPUnit入门:原理、安装与测试用例编写指南

本文详解PHP单元测试框架PHPUnit的入门知识,涵盖其命令行运行特性、PHAR包执行原理及TestCase类加载机制。通过具体实例演示如何编写符合规范的测试类,利用assertEquals等断言方法验证生产代码行为,帮助开发者快速掌握单元测试的核心流程与最佳实践。

2026.07.18 266
PHP使用PHPUnit进行单元测试完整指南

本文详细介绍在Linux环境下为PHP项目配置PHPUnit并进行单元测试的完整流程。内容包括通过phar包安装phpunit命令、创建包含断言逻辑的UnitTest.php文件,以及执行测试并分析输出结果以定位代码错误的具体步骤。

2026.10.24 180

专题推荐

更多
PHP 类与对象定义及继承

先看类声明、对象实例与属性访问。理解对象的创建和销毁后,再读继承、方法重载和关键字对照。已有代码遇到继承行为差异时,可进一步查看 final 方法与反射实例。

PHP 定时任务配置与运行

先确定任务运行间隔以及是否允许重叠。固定时间触发先看 Cron 案例,框架内和常驻服务再读对应示例。

Yii2 队列配置与常驻运行

先用一个最小任务跑通入队和消费,再检查 Web 与 Console 是否加载了相同的队列配置。确认命令能手动运行后再配置 Supervisor,最后验证进程重启时的处理情况。

PHP Session 过期时间设置方法

浏览器关闭、服务端回收和业务规定的闲置超时,可能在不同时间发生。对照配置项与应用层时间戳的做法,检查会话何时仍可读、何时应要求重新登录。

PHP URL 编码和解码方法

URL 路径片段和查询参数对空格的处理方式不同。先比较 urlencode 与 rawurlencode,再沿解码过程核对中文、加号和百分号,检查地址是否被重复编码或提前解码。

在线工具箱

更多
键码查询
键码查询

按下键盘按键时查看浏览器记录的键名和事件信息。

.env 配置检查
.env 配置检查

本地检查 .env 键值语法、引号、重复键及空值,预览解析结果,辅助排查 PHP 和 Laravel 环境配置。

进制转换
进制转换

转换二进制、十进制、十六进制等数值表示,辅助程序调试与进制学习。

HTML 标签安全清理
HTML 标签安全清理

清理 HTML 片段中的标签或危险内容,辅助整理待展示的文本。

文件 Base64 转换
文件 Base64 转换

把文件转为 Base64 文本,也可将编码内容还原为文件,方便接口传输与调试。