【发布时间】:2015-12-29 12:57:41
【问题描述】:
我有一个类,它有一个使用 PHP 的全局 file_get_contents 函数的方法。我需要在类上测试方法,而不是实际调用全局函数。
我知道我可以使用命名空间来覆盖从 file_get_contents 返回的内容,但是我的测试已经在一个单独的命名空间中,所以我不能简单地将命名空间与类匹配。
这里有一些代码:
类
<?php
namespace MyVendor\MyProject;
class MyClass
{
private $someProperty;
public function __construct($override = '')
{
$this->someProperty = $override;
}
public function myMethod()
{
$request = 'http://example.com';
$response = $this->someMethodUsingGlobals($request);
// Do something with the response..
}
public function someMethodUsingGlobals($url)
{
return json_decode(file_get_contents($url),true)['results'][0];
}
}
测试
<?php
namespace MyProjectTests;
public function test_it_does_something_with_the_response()
{
$sut = new MyClass();
$response = $sut->myMethod();
$this->assertEquals('Some expectation', $response);
}
我需要在课堂上模拟 someMethodUsingGlobals() 方法,但不完全确定如何去做。
【问题讨论】:
-
很难模拟私有方法。如果问题是 file_get_content 我建议你使用vfsStream library。你可以找到一篇关于使用它进行测试的好文章here。如果您需要一些帮助来将其集成到您的测试中,请告诉我。
-
老实说,将该方法更改为 public 很好。这不是我面临的问题的原因(更新操作)。
-
好的,我们可以对测试类进行部分模拟。好的?您需要一个工作示例吗?
-
这就是我正在努力解决的问题。模拟被测类,而不实例化另一个扩展被测类的类。举个例子就好了。
标签: unit-testing testing mocking phpunit