The question like in the title. The example method I have problems testing is: https://github.com/rzajac/phptools/blob/master/src/Cli/Interaction.php#L36
1条回答 默认 最新
- doutangxi2144 2015-11-05 17:59关注
You can mock the fgets() if you have namespaces in use.
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; } }
The Test file:
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 discusses a socket example as well that handles exceptions.
本回答被题主选为最佳回答 , 对您是否有帮助呢?解决 无用评论 打赏 举报