Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/php/273.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 symfony_Php_Symfony_Phpunit - Fatal编程技术网

尝试捕获私有方法phpunit symfony

尝试捕获私有方法phpunit symfony,php,symfony,phpunit,Php,Symfony,Phpunit,我有以下代码: public function addSomething($paramDto) { try { $this->privateMethod($param); } catch(\Exception $e) { return ['error' => true, 'messages' => [$e->getMessage()]]; } return ['error' => false, 'messages'

我有以下代码:

public function addSomething($paramDto) {
   try {
       $this->privateMethod($param);
   } catch(\Exception $e) {
       return ['error' => true, 'messages' => [$e->getMessage()]];
   }
   return ['error' => false, 'messages' => 'success'];
}

private function privateMethod($param) {
    if(!$param) {
        throw new \Exception('errorMessage');
    }
}

我试图测试addSomething方法,catch块返回什么,我不想测试private方法。

 public function testAddSomethingThrowError($paramDto) {
    $param = \Mockery::mock('MyEntity');

    $method = new \ReflectionMethod(
        'MyService', 'privateMethod'
    );

    $method->setAccessible(TRUE);

    $this->expectException(\Exception::class);
    $this->getMyService()
        ->shouldReceive($method->invoke($param)
        ->withAnyArgs()
        ->andThrow(\Exception::class);
     $this->getMyService()->addSomething($paramDto);
 }
问题是,如果我运行测试,它会覆盖if语句中的私有方法并返回异常,但是addSomething方法中的catch方法没有覆盖,实际上它根本没有覆盖addSomething方法

我使用的是sebastian bergmann phpunit框架


我做错了什么?

正确答案应该是Jakub Matczak的答案:


“您想”断言公共方法是否返回了它确实正在返回的消息“。这样做没有意义。将您的测试类视为黑盒,不可能检查其来源。然后根据如何使用它的公共接口来进行测试。”

为什么您甚至想测试私有方法?单元测试应该测试类的公共接口,这样就可以间接测试私有接口。私有方法只是为了让代码干净。我不想测试私有方法,我想断言catch块中返回的消息。你想“断言公共方法是否返回它确实返回的消息”。那样做没有意义。将测试类视为黑箱,不可能检查其来源。然后根据如何使用它的公共接口进行测试。哦,我明白了。我不知道。谢谢你的快速回复。