2013-04-10 30 views
3

所以我有这个工厂类实现的Zend \的ServiceManager \ FactoryInterface:如何对一个依赖常量的工厂类进行单元测试?

class GatewayFactory implements FactoryInterface 
{ 

    public function createService(ServiceLocatorInterface $serviceLocator) 
    { 
     $config = new Config($serviceLocator->get('ApplicationConfig')); 
     if ('phpunit' === APPLICATION_ENV) { 
      return new Gateway($config, new Mock()); 
     } 
     return new Gateway($config); 
    } 

} 

它总是返回网关实例,但增加了一个模拟适配器作为第二个参数时APPLICATION_ENV不变的是“PHPUnit的”。

我正在我的单元测试此配置:

<?xml version="1.0" encoding="UTF-8"?> 
<phpunit bootstrap="tests/unit/Bootstrap.php" colors="true" backupGlobals="false" backupStaticAttributes="false" syntaxCheck="false"> 
    <testsuites> 
     <testsuite name="mysuite"> 
      <directory suffix="Test.php">tests/unit</directory> 
     </testsuite> 
    </testsuites> 
    <php> 
     <const name="APPLICATION_ENV" value="phpunit"/> 
    </php> 
</phpunit> 

为此APPLICATION_ENV被设置为 “PHPUnit的”。当常数不同时,我如何为案例编写测试?

我可以测试,如果条件,但我无法弄清楚如何测试的情况下,当它不if条件往里走:

class GatewayFactoryTest extends PHPUnit_Framework_TestCase 
{ 

    public function testCreateServiceReturnsGatewayWithMockAdapterWhenApplicationEnvIsPhpunit() 
    { 
     $factory = new GatewayFactory(); 
     $gateway = $factory->createService(Bootstrap::getServiceManager()); 
     $this->assertInstanceOf('Mock', $gateway->getAdapter()); 
    } 

    public function testCreateServiceReturnsGatewayWithSockerAdapterWhenApplicationEnvIsNotPhpunit() 
    { 
     // TODO HOW TO DO THIS? 
    } 

} 
+0

为什么不使用环境变量而不是常量?这样你可以在你的测试中使用createService调用的任何一侧的'putenv'。 – Crisp 2013-04-11 08:20:51

回答

3

你不应该写代码,它只是用来在测试中。你应该编写可以测试的代码。

你可以做这样的事情。不过,我也会看看Gateway这个类。为什么它有时需要额外的对象?

相关问题