phpunit - mockbuilder - set mock object internal property(phpunit - mockbuilder - 设置模拟对象内部属性)
问题描述
是否可以创建一个禁用构造函数并手动设置受保护属性的模拟对象?
Is it possible to create a mock object with disabled constructor and manually setted protected properties?
这是一个愚蠢的例子:
class A {
protected $p;
public function __construct(){
$this->p = 1;
}
public function blah(){
if ($this->p == 2)
throw Exception();
}
}
class ATest extend bla_TestCase {
/**
@expectedException Exception
*/
public function testBlahShouldThrowExceptionBy2PValue(){
$mockA = $this->getMockBuilder('A')
->disableOriginalConstructor()
->getMock();
$mockA->p=2; //this won't work because p is protected, how to inject the p value?
$mockA->blah();
}
}
所以我想注入受保护的 p 值,所以我不能.我应该定义 setter 还是 IoC,或者我可以用 phpunit 来做?
So I wanna inject the p value which is protected, so I can't. Should I define setter or IoC, or I can do this with phpunit?
推荐答案
你可以使用反射将属性设为public,然后设置所需的值:
You can make the property public by using Reflection, and then set the desired value:
$a = new A;
$reflection = new ReflectionClass($a);
$reflection_property = $reflection->getProperty('p');
$reflection_property->setAccessible(true);
$reflection_property->setValue($a, 2);
无论如何,在您的示例中,您不需要为要引发的异常设置 p 值.您正在使用模拟来控制对象的行为,而无需考虑其内部.
Anyway in your example you don't need to set p value for the Exception to be raised. You are using a mock for being able to take control over the object behaviour, without taking into account it's internals.
因此,不是设置 p = 2 来引发异常,而是将模拟配置为在调用 blah 方法时引发异常:
So, instead of setting p = 2 so an Exception is raised, you configure the mock to raise an Exception when the blah method is called:
$mockA = $this->getMockBuilder('A')
->disableOriginalConstructor()
->getMock();
$mockA->expects($this->any())
->method('blah')
->will($this->throwException(new Exception));
最后,奇怪的是你在 ATest 中模拟 A 类.您通常模拟您正在测试的对象所需的依赖项.
Last, it's strange that you're mocking the A class in the ATest. You usually mock the dependencies needed by the object you're testing.
希望这会有所帮助.
这篇关于phpunit - mockbuilder - 设置模拟对象内部属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:phpunit - mockbuilder - 设置模拟对象内部属性
基础教程推荐
- 在 Woocommerce 中根据运输方式和付款方式添加费用 2021-01-01
- 通过 PHP SoapClient 请求发送原始 XML 2021-01-01
- Libpuzzle 索引数百万张图片? 2022-01-01
- 在多维数组中查找最大值 2021-01-01
- 超薄框架REST服务两次获得输出 2022-01-01
- 在 PHP 中强制下载文件 - 在 Joomla 框架内 2022-01-01
- XAMPP 服务器不加载 CSS 文件 2022-01-01
- 如何在 PHP 中的请求之间持久化对象 2022-01-01
- WooCommerce 中选定产品类别的自定义产品价格后缀 2021-01-01
- mysqli_insert_id 是否有可能在高流量应用程序中返回 2021-01-01