对象的模拟方法和返回对象值取决于方法参数

时间:2016-12-20 14:53:17

标签: php unit-testing symfony

有方法模拟方法和返回值取决于方法参数吗?我需要这个来模拟容器并获得服务。我试着这样做:

$container = $this
        ->getMockBuilder(Container::class)
        ->getMock();

$container
        ->expects($this->any())
        ->method('get')
        ->with('logger')
        ->willReturn($this->loggerMock)//this is logger object
    ;
$container->expects($this->any())
        ->method('get')
        ->with('database')
        ->will($this->returnValue(self::$pdo));//database object

$this->dataProviderFactory = new DataProviderFactory($container);

当我这样称呼:print_r($ container-> get('logger'));应该有Logger对象。

但这不起作用。我收到以下错误:

方法名称的期望失败等于调用零次或多次

Parameter 0 for invocation Symfony\Component\DependencyInjection\Container::get('logger', 1) does not match expected value.
Failed asserting that two strings are equal.
Expected :'database'
Actual   :'logger'

1 个答案:

答案 0 :(得分:2)

您可以通过使用回调函数来处理在运行时传递给方法的参数。

尝试以下方法:

$container = $this
    ->getMockBuilder(Container::class)
    ->getMock();

$container
    ->expects($this->any())
    ->method('get')
    ->will($this->returnCallback(function ($arg) {
        $map = [
            'logger'   => $this->loggerMock,
            'database' => $this->returnValue(self::$pdo)
        ];
        return $map[$arg];
    }))
;