我有以下代码:
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块返回的内容,我不想测试私有方法。
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语句中的private方法并返回异常,但我的addSomething方法中的catch方法没有被覆盖,实际上它根本不包括addSomething方法。
我使用的是塞巴斯蒂安bergmann phpunit框架。
我做错了什么?
答案 0 :(得分:0)
正确答案应该是Jakub Matczak的回答:
“你想”断言公共方法是否正在返回它确实正在返回的消息“。这样做没有任何意义。将测试的类视为黑盒而无法检查其来源。然后根据如何让它使用其公共接口工作。“