Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/php/288.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Phpunit:私有方法运行了多少次?_Php_Phpunit - Fatal编程技术网

Phpunit:私有方法运行了多少次?

Phpunit:私有方法运行了多少次?,php,phpunit,Php,Phpunit,以及测试: class TestMe { private function a ($a, $b) { return $a+$b; } private function b ($a, $b) { return $a*$b; } public function serial ($a, $b) { $this->a ($a,$b); $this->b ($a,

以及测试:

class TestMe
{
    private function a ($a, $b)
    {
        return $a+$b;
    }

    private function b ($a, $b)
    {
        return $a*$b;
    }

    public function serial ($a, $b)
    {
        $this->a ($a,$b);
        $this->b ($a,$b);
    }
testSerial
中,我想检查
a()
b()
是否触发一次:

public function testA()
{
    $ref = new ReflectionClass ('TestMe');
    $method = $classNameOrObject->getMethod('a');
    $method->setAccessible(true);
    $this->assertEquals (2, $method->invokeArgs (1,1));
}

public function testB()
{
    $ref = new ReflectionClass ('TestMe');
    $method = $classNameOrObject->getMethod('b');
    $method->setAccessible(true);
    $this->assertEquals (1, $method->invokeArgs (1,1));
}

public function testSerial()
{
    $sut = new TestMe();
    $sut->testB();
}

这在现在是不可能的,因为私有方法不能被模仿。有什么想法吗?我可以用
ReflectionClass
实现,但这样会使原始函数无法运行。

不要模仿私有方法。甚至不要尝试测试它们。它们是你不需要关心的课堂细节。你所关心的是公共职能部门做什么。在您的示例中,它实际上什么都不是(它调用两个返回值的方法,并且对它们不做任何处理)

但是,假设该方法减去这两个值。因此,函数如下所示:

$stub = $this->getMock ('TestMe', array('a', 'b'));
$stub->expects($this->once())->method('a');
$stub->expects($this->once())->method('b');
public function serial ($a, $b)
{
    $c = $this->a ($a,$b);
    $d = $this->b ($a,$b);

    return $c - $d;
}
示例测试可能如下所示:

$stub = $this->getMock ('TestMe', array('a', 'b'));
$stub->expects($this->once())->method('a');
$stub->expects($this->once())->method('b');
public function serial ($a, $b)
{
    $c = $this->a ($a,$b);
    $d = $this->b ($a,$b);

    return $c - $d;
}
我关心的只是函数serial返回(或执行)的内容。我不在乎私人活动。如果出于某种原因,您决定删除上述测试通过的私有函数。或者,如果
serial()
中的额外功能被移动到新的私有函数中,则测试将通过

指定调用私有函数会降低测试的可用性,并使代码重构更加困难。重构不应该改变功能,这样就不会导致测试失败。指定私有方法意味着您必须确定测试是否由于删除私有方法而失败,或者您引入了错误

如果你的私人功能非常复杂,你会觉得需要单独测试。这是一种代码味道,也许应该将这些方法提取到它们自己的类中