【问题标题】:Phpunit mock private functionPhpunit 模拟私有函数
【发布时间】:2016-01-30 15:34:27
【问题描述】:

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

我想模拟私有函数,这样我就可以将值返回给调用私有函数的公共函数。我通过创建一个具有相同函数但具有我希望函数返回的值的新类来尝试它。

这是我的代码

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

这是我想调用的类以返回一些值。

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

以及我尝试模拟 privte 函数的设置

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

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

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

【问题讨论】:

标签: php testing phpunit


【解决方案1】:

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

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

【讨论】:

    猜你喜欢
    • 2011-10-30
    • 2017-01-13
    • 2014-12-13
    • 2016-03-21
    • 2015-10-03
    • 2020-05-08
    • 2015-12-18
    • 1970-01-01
    • 2013-02-23
    相关资源
    最近更新 更多