我有一个类输出到STDERR
,但我无法找到让 PHPUnit 测试其输出的方法。
班上,PHPUnit_Extensions_OutputTestCase
,也没起作用。
我没有看到缓冲的方法stderr
尽你所能stdout
,所以我会重构你的类,将执行实际输出的调用移至新方法。这将允许您在测试期间模拟该方法,以使用缓冲的方法验证输出或子类。
例如,假设您有一个列出目录中文件的类。
class DirLister {
public function list($path) {
foreach (scandir($path) as $file) {
echo $file . "\n";
}
}
}
首先,提取调用echo
。使其受到保护,以便您可以覆盖和/或模拟它。
class DirLister {
public function list($path) {
foreach (scandir($path) as $file) {
$this->output($file . "\n");
}
}
protected function output($text) {
echo $text ;
}
}
其次,在测试中模拟或子类化它。如果您有一个简单的测试或者不希望有很多调用,则模拟很容易output
。如果您有大量输出需要验证,则通过子类化来缓冲输出会更容易。
class DirListTest extends PHPUnit_Framework_TestCase {
public function testHomeDir() {
$list = $this->getMock('DirList', array('output'));
$list->expects($this->at(0))->method('output')->with("a\n");
$list->expects($this->at(1))->method('output')->with("b\n");
$list->expects($this->at(2))->method('output')->with("c\n");
$list->list('_files/DirList'); // contains files 'a', 'b', and 'c'
}
}
压倒一切output
缓冲所有$text
进入内部缓冲区作为读者的练习。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)