我試圖用vfsStream來模擬文件系統操作(實際上是從php://輸入讀取),但缺乏體面的文檔和示例實際上阻礙了我。試圖用VFSStream測試文件系統操作
從類我測試的有關代碼如下:
class RequestBody implements iface\request\RequestBody
{
const
REQ_PATH = 'php://input',
protected
$requestHandle = false;
/**
* Obtain a handle to the request body
*
* @return resource a file pointer resource on success, or <b>FALSE</b> on error.
*/
protected function getHandle()
{
if (empty ($this -> requestHandle))
{
$this -> requestHandle = fopen (static::REQ_PATH, 'rb');
}
return $this -> requestHandle;
}
}
我用我的PHPUnit的測試設置如下:
protected function configureMock()
{
$mock = $this -> getMockBuilder ('\gordian\reefknot\http\request\RequestBody');
$mock -> setConstructorArgs (array ($this -> getMock ('\gordian\reefknot\http\iface\Request')))
-> setMethods (array ('getHandle'));
return $mock;
}
/**
* Sets up the fixture, for example, opens a network connection.
* This method is called before a test is executed.
*/
protected function setUp()
{
\vfsStreamWrapper::register();
\vfsStream::setup ('testReqBody');
$mock = $this -> configureMock();
$this -> object = $mock -> getMock();
$this -> object -> expects ($this -> any())
-> method ('getHandle')
-> will ($this -> returnCallback (function() {
return fopen ('vfs://testReqBody/data', 'rb');
}));
}
在實際測試(它調用間接觸發getHandle()的方法)我嘗試設置VFS並按如下方式運行斷言:
public function testBodyParsedParsedTrue()
{
// Set up virtual data
$fh = fopen ('vfs://testReqBody/data', 'w');
fwrite ($fh, 'test write 42');
fclose ($fh);
// Make assertion
$this -> object -> methodThatTriggersGetHandle();
$this -> assertTrue ($this -> object -> methodToBeTested());
}
這只是導致測試掛起。
顯然我在這裏做的事情非常錯誤,但鑑於文檔的狀態,我無法弄清楚我打算做什麼。這是由vfsstream引起的,還是phpunit嘲笑我需要在這裏看的東西?
VFSStream當你不需要調用
vfsStreamWrapper::register();
是所有子類和命名空間等一切都必須是一個不必要的複雜的工具包片一流的方法。它是一個包裝的包裝。我只寫了一個基於php接口StreamWrapper的類,這足以完成工作。另請參閱:http://php.net/manual/en/class.streamwrapper.php – Codebeat 2013-08-02 23:01:45