所以我有这个工厂类实现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条件,但我不知道如何测试不属于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?
}
}
您不应该编写只在测试中使用的代码。你应该编写可以被测试的代码。
你可以这样做。
public function createService(ServiceLocatorInterface $serviceLocator, $mock = null)
{
$config = new Config($serviceLocator->get('ApplicationConfig'));
return new Gateway($config, $mock);
}
我也想看看Gateway
类。为什么它有时需要一个额外的对象?