在构造函数中调用的phpunit mock方法

时间:2015-07-14 16:00:37

标签: constructor mocking phpunit

我测试了一个配置类,它正在解析配置文件,并允许我获取应用程序的各种设置。

我的目标是模拟Config类的parse()方法,该方法在构造函数中调用,并设置此方法在构造函数中返回的内容。

这样,它阻止file_get_contents()被调用(在parse()方法中),并使我能够拥有一个Config类,其config属性已设置为包含属性数组。

但我还没有成功。

以下是代码:

配置类:

<?php namespace Example;

use Symfony\Component\Yaml\Parser;

class Config
{

private $parser;
private $config;

public function __construct(Parser $parser, $filePath)
{
    $this->parser = $parser;
    $this->config = $this->parse($filePath);
}

public function parse($filePath)
{
    $fileAsString = file_get_contents($filePath);

    if (false === $fileAsString) {
        throw new \Exception('Cannot get config file.');
    }

    return $this->parser->parse($fileAsString);
}

public function get($path = null)
{
    if ($path) {
        $config = $this->config;

        $path = explode('/', $path);

        foreach ($path as $bit) {
            if (isset($config[$bit])) {
                $config = $config[$bit];
            }
        }

        return $config;

    }

    return false;
    }

}

测试:

<?php namespace Example;

class ConfigTest extends \PHPUnit_Framework_TestCase
{

    private function getConfigTestMock($configAsArray)
    {
        $parser = $this->getMockBuilder('\Symfony\Component\Yaml\Parser')
            ->getMock();

        $configMock = $this->getMockBuilder('Example\Config')
            ->setConstructorArgs([$parser, $configAsArray])
            ->setMethods(['parse', 'get'])
            ->getMock();

        $configMock->expects($this->once())
            ->method('parse')
            ->willReturn($configAsArray);

        return $configMock;
    }

    /**
     * @test
     */
    public function get_returns_false_if_no_path_given()
    {
        $configMock = $this->getConfigTestMock(['param1' => 'value1']);

        // Testing further...

    }
}

1 个答案:

答案 0 :(得分:1)

要测试Config类,您只需要模拟Parser并使用真正的Config类。例如:

<?php


namespace Acme\DemoBundle\Tests;


use Acme\DemoBundle\Example\Config;

class ConfigTest extends \PHPUnit_Framework_TestCase
{

    private function getConfigTestMock($configAsArray)
    {
        $parser = $this->getMockBuilder('\Symfony\Component\Yaml\Parser')
            ->getMock();


        $parser->expects($this->once())
            ->method('parse')
            ->willReturn($configAsArray);

        $configMock = new Config($parser,"fakePath");

        return $configMock;
    }

    /**
     * @test
     */
    public function get_returns_false_if_no_path_given()
    {
        $configMock = $this->getConfigTestMock(['param1' => 'value1']);
        $this->assertEquals("value1",$configMock->get("param1"));

        // Testing further...

    }
}

希望这个帮助