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 条件,但我不知道如何测试一个不在 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?
    }

}
4

1 回答 1

3

您不应该编写仅用于测试的代码。您应该编写可以测试的代码。

你可以做这样的事情。

public function createService(ServiceLocatorInterface $serviceLocator, $mock = null)
{
    $config = new Config($serviceLocator->get('ApplicationConfig'));

    return new Gateway($config, $mock);
}

不过,我也想看看这Gateway门课。为什么它有时需要一个额外的对象?

于 2013-04-11T10:03:48.493 回答