我正在使用 PHPUnit,但很难让它为用作数据存储的对象创建好的模拟和 stub 。
例子:
class urlDisplayer {
private $storage;
public function __construct(IUrlStorage $storage) { $this->storage = $storage; }
public function displayUrl($name) {}
public function displayLatestUrls($count) {}
}
interface IUrlStorage {
public function addUrl($name, $url);
public function getUrl($name);
}
class MysqlUrlStorage implements IUrlStorage {
// saves and retrieves from database
}
class NonPersistentStorage implements IUrlStorage {
// just stores for this request
}
例如,如何让 PHPUnit stub 在具有不同 $name 的两个调用中返回多个可能的值?
编辑:示例测试:
public function testUrlDisplayerDisplaysLatestUrls {
// get mock storage and have it return latest x urls so I can test whether
// UrlDisplayer really shows the latest x
}
在这个测试中,模拟应该返回一些 url,但是在文档中我只返回一个值。
最佳答案
您的问题不是很清楚 - 但我假设您在问如何使用 phpunit 的模拟对象在不同情况下返回不同的值?
PHPUnit 的模拟类允许您指定自定义函数(即:回调函数/方法)——实际上它的功能是无限的。
在下面的示例中,我创建了一个模拟 IUrlStorage 类,该类将在每次调用时返回其存储中的下一个 url。
public function setUp()
{
parent::setUp();
$this->fixture = new UrlDisplayer(); //change this to however you create your object
//Create a list of expected URLs for testing across all test cases
$this->expectedUrls = array(
'key1' => 'http://www.example.com/url1/'
, 'key2' => 'http://www.example.net/url2/'
, 'key3' => 'http://www.example.com/url3/'
);
}
public function testUrlDisplayerDisplaysLatestUrls {
//Init
$mockStorage = $this->getMock('IUrlStorage');
$mockStorage->expects($this->any())
->method('getUrl')
->will( $this->returnCallback(array($this, 'mockgetUrl')) );
reset($this->expectedUrls); //reset array before testing
//Actual Tests
$this->assertGreaterThan(0, count($this->expectedUrls));
foreach ( $this->expectedUrls as $key => $expected ) {
$actual = $this->fixture->displayUrl($key);
$this->assertEquals($expected, $actual);
}
}
public function mockGetUrl($name)
{
$value = current($this->expectedUrls);
next($this->expectedUrls);
//Return null instead of false when end of array is reached
return ($value === false) ? null : $value;
}
或者,有时更容易创建一个模拟必要功能的真实类。这对于定义明确的小型接口(interface)尤其容易。
在这种特定情况下,我建议改用以下类:
class MockStorage implements IUrlStorage
{
protected $urls = array();
public function addUrl($name, $url)
{
$this->urls[$name] = $url;
}
public function getUrl($name)
{
if ( isset($this->urls[$name]) ) {
return $this->urls[$name];
}
return null;
}
}
?>
然后在您的单元测试类中,您只需实例化您的夹具,如下所示:
public function setUp() {
$mockStorage = new MockStorage();
//Add as many expected URLs you want to test for
$mockStorage->addUrl('name1', 'http://example.com');
//etc...
$this->fixture = new UrlDisplayer($mockStorage);
}
关于php - PHP中的单元测试数据存储,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1156038/