针对受保护属性进行单元测试

问题描述 投票:0回答:1

如何编写好的 OOP 代码、SOLID、封装、松散耦合等导致的想法

  • 不使用公共财产
  • 使用尽可能少的吸气剂

假设我们有代码

class Some
{
  protected int $x;
  protected int $y;
 
  public function __construct(int $x, int $y) {
    $this->x = $x;
    $this->y = $y;
  }

  public function swapXY() : void {
    $r = $this->x;
    $this->x = $this->y;
    $this->y = $r;
  }
}

测试不起作用

class SomeTest extends \PHPUnit\Framework\TestCase
{
    public function testSwap() {
        $obj = new Some(5, 6);
        $obj->swapXY();
        $this->assertSame(6, $obj->x);  // ERROR
        $this->assertSame(5, $obj->y);

        
    }
}

自从 phpunit 9.0 放弃了像assertAttributeSame()这样的支持方法以来,如何使用 phpunit 测试 Some::swapXY() 方法?

我不是在这里讨论测试受保护/私有方法。 只有这种情况:我们通过对象的方法向对象发送信号。 这项工作的后置条件不是返回某个值,而是将某些对象属性设置为另一个值。

使用反射会有所帮助,但为什么它被认为是一个糟糕的主意,以至于被从测试框架中剔除? 谢谢

尝试用推荐的方式解决

php unit-testing phpunit
1个回答
0
投票

将此逻辑作为公共类 API 的一部分进行测试。 X 和 Y 必须在某些公共方法中的某个地方使用。而是测试一下。

© www.soinside.com 2019 - 2024. All rights reserved.