2013-02-21 61 views
2

我想测试一个调用exec()的php函数,那么最好的方法是什么?我用它来获得的git describe结果:为对象执行exec创建测试()

class Version 
{ 
    public function getVersionString() 
    { 
     $result = exec('git describe --always'); 

     if (false !== strpos($result, 'fatal')) { 
      throw new RuntimeException(sprintf(
       'Git describe returns error: %s', 
       $result 
      )); 
     } 

     return $result; 
    } 
} 

所以我想如果执行命令来测试,并在发生错误时,抛出异常(即“预期”的行为和“例外”的行为)。

class VersionTest extends PHPUnit_Framework_TestCase 
{ 
    public function testVersionResultsString() 
    { 
     $version = new Version(); 
     $result = $version->getVersionString(); 

     $this->assertEquals('...', $result); 
    } 

    public function testVersionResultHasFatalErrorThrowsException() 
    { 
     // trigger something that will cause the fatal 
     $this->setExpectedException('RuntimeException'); 

     $version = new Version(); 
     $result = $version->getVersionString(); 
    } 
} 

过程中的类和测试的是真正比较复杂一点,但本质是捕捉exec()地方。任何想法如何?

回答

2

如果你使用的命名空间,有一招模拟内置功能,描述如下:https://stackoverflow.com/a/5337635/664108

所以,基本上你可以用自己的函数,它的返回值将被指定替换exec您试验。