设置可访问并不会使私人属性可用时嘲弄

时间:2016-12-23 10:28:35

标签: php unit-testing testing phpunit mockery

我想要嘲笑一个班来测试它。它有private property detail,由网络请求设置。我试图通过模拟property来测试其他methods之前设置json file。一切都工作正常,但是,当它是一个私人财产时,我似乎无法设置该属性,但当它是受保护的属性时,它就可以工作。

$mockedClass = \Mockery::mock( Myclass::class )->makePartial();
$reflection = new \ReflectionClass($mockedClass);
$property = $reflection->getProperty( 'detail' );
$property->setAccessible(true);
$property->setValue($mockedClass, $jsonData ); 

所以当detailprivate property时,Mockery会抛出Property detail does not exist,但当我detail受到保护时,它会有效。

我不想让detail成为protected property,因为它不需要,但我需要这样做才能测试它。

当我在某处阅读时,就像你母亲所说的那样,不要暴露你的私人"。我不想暴露我的私人。

1 个答案:

答案 0 :(得分:1)

尝试稍微改变一下:

$mockedClass = \Mockery::mock( Myclass::class )->makePartial();
$reflection = new \ReflectionClass(Myclass::class); // Pass the class name, not the actual mock object
$property = $reflection->getProperty( 'detail' );
$property->setAccessible(true);
$property->setValue($mockedClass, $jsonData ); 
相关问题