所以我有这个实现 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?
}
}