标题中的问题。我在测试时遇到问题的示例方法是:https://github.com/rzajac/phptools/blob/master/src/Cli/Interaction.php#L36
答案 0 :(得分:0)
如果您正在使用名称空间,则可以模拟fgets()。
namespace My\Namespace;
class SomeClass
{
public static function getPassword($prompt = '')
{
echo $prompt;
\system('stty -echo');
// Notice how the global function "fgets()" is called without the leading backslash
// (relative instead of absolute call in a namespaced environment).
// This will let us later mock the call
$pass = fgets(STDIN);
\system('stty echo');
return $pass;
}
}
测试文件:
namespace My\Namespace {
// And this here, does the trick: it will override the fgets()
// function in your code *just for the namespace* where you are defining it.
function fgets($Handle) {
return 'Pa$$Word'; // Password Text for testing
}
include_once './SomeClass.php';
class Test_SomeClass extends \PHPUnit_Framework_TestCase
{
/**
* This will test the success case.
* @test
*/
public function testPass()
{
$dummy = new \My\Namespace\SomeClass;
$this->assertEqual('Pa$$Word', $dummy->getPassword());
}
}
This Post讨论了一个处理异常的套接字示例。