所以我有这个工厂类实现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”时,它总是返回Gateway实例,但会添加一个模拟适配器作为第二个参数。
我正在使用此配置运行我的单元测试:
<?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条件但我无法弄清楚当它不进入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 :(得分:3)
您不应该编写仅在测试中使用的代码。你应该编写可以测试的代码。
你可以这样做。
public function createService(ServiceLocatorInterface $serviceLocator, $mock = null)
{
$config = new Config($serviceLocator->get('ApplicationConfig'));
return new Gateway($config, $mock);
}
我也会看一下Gateway
课程。为什么有时需要一个额外的对象?