Phpunit 模拟私有函数

Phpunit mock private function

我的问题是。我有一个 class 我只想测试我想测试的函数是在我想测试的 class 中调用私有函数。私有函数调用另一个 class 函数。

我想模拟私有函数,这样我就可以 return 调用私有函数的 public 值。我通过创建一个具有相同功能但具有我希望该功能的值的新 class 来尝试 return.

这是我的代码

//function i want to test
public function checksomedata($objectID){
        $config = $this->theprivatefunction($objectID,'id');
        return $config;
    }

我想模拟的私有函数

private function theprivatefunction($objectID,'id'){
//do some code here. nothing special
//return the value here
}

这是我的测试

public function testCheckObjectAcces() {
        $objectID = '12';
      $this->testclass->checksomedata($objectID);
    }

这是我的 class 我想调用 return 一些值。

public function theprivatefunction(){
        $result = "THIS VALUE NEEDS TO BE RETURNED";
        return $result;
    }

和我尝试模拟 priavte 函数的设置

$this->mockextended = new \stdClass();
        $this->mockextended = new MOCKEXTENDEDCLASSES();
        $this->testclass->theprivatefunction() = $this->mockextended->theprivatefunction();

在我的设置中,我希望代码认为 $this->testclass->theprivatefunction()$this->mockextended->theprivatefunction();

所以当函数调用私有函数时需要重定向到$this->mockextended->theprivatefunction();

这个问题有两种解决方法:

  1. 将私有方法作为调用 public 方法的一部分进行单元测试。单元测试的目标是测试 class 的 public API。您通过 public API 测试私有方法,因此应该测试 return 值,包括从私有方法编辑的值 return。如果私有方法依赖于某些外部状态,那么您要确保在测试开始和结束时分别设置(和拆除)状态。
  2. 有时,私有方法是无法直接测试的问题。例如,我最近有一个实例,其中我编写的方法是从 stdin 读取数据。据我所知,您不能在测试中为 stdin 赋值,因此我不得不将对 stdin 的读取拆分为一个单独的方法。然后,我创建了一个测试存根,它将父方法覆盖为 return 预定义值。这使您可以控制您通常不会拥有的私有方法。