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);
    }

}

常に Gateway インスタンスを返しますが、APPLICATION_ENV 定数が "phpunit" の場合、2 番目のパラメーターとしてモック アダプターを追加します。

この構成で単体テストを実行しています。

<?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 に答える