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



有方法可以模拟方法和返回值的返回值参数吗?我需要这个来模拟容器并获得服务。我尝试这样做:

$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'));应该有记录器对象。

但这不起作用。我在下面有错误:

方法名称失败的期望与调用零或更多次调用时

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

您可以通过使用回调函数对运行时传递给该方法的参数作用来执行此操作。

尝试以下内容:

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

最新更新