laravel 模拟多个 shouldReturn() 语句

laravel mocks with multiple shouldReturn() statements

我正在尝试创建一个 laravel 模拟,它有两个 shouldRecieve() 语句

像这样

$mock = $this->mock(Service::class, function (MockInterface $mock) {

$mock->shouldReceive('init')->once();

$mock->shouldReceive('process')->once();
});

我尝试了几种变体,但无论尝试什么,它都只模拟了其中一个函数

shouldrecieve 可以将多个参数作为一个数组,但如果我这样做,则没有明显的方法来为每个参数设置一组不同的 asserts/function(once()、with()、andReturns() 等)模拟函数

我正在使用 laravel 服务容器实例化 Service::class 即

App::make(Service::class);

我怎样才能完成这项工作

这个很棒的库没有解释你可以像 closure 一样向 ::mock 发送第二个参数并且它会做一些事情真是太棒了......糟糕的文档......

documentation 什么也没说,所以要放弃这种行为,请尝试以正常方式进行,而不是您的代码,试试这个:

$mock = Mockery::mock(Service::class);

$this->bind(Service::class, function () use ($mock) {
    $mock->shouldReceive('init')->once();
    $mock->shouldReceive('process')->once();

    return $mock;
});

我已经解决了这个问题

问题是我的 Service::class 有一个 ServiceBuilder::class 一旦服务构建器 class 被实例化,一个函数 returns 服务构建器的实例在 returns 服务

的函数之前运行

像这样

$serviceBuilder = App::make(ServiceBuilder::class)
$servieBuilder = $serviceBuilder->setup();
$service = $serviceBuilder->build();

为了使这个工作这个代码

$mock = Mockery::mock(Service::class);

    $this->bind(Service::class, function () use ($mock) {
        $mock->shouldReceive('init')->once();
        $mock->shouldReceive('process')->once();
    
        return $mock;
    });

必须成为

$builderMock = Mockery::mock(ServiceBuilder::class);
$mock = Mockery::mock(Service::class);

    $this->bind(ServiceBuilder::class, function () use (builderMock) {
        $builderMock->shouldReceive('setup')->once()->andReturn($builderMock);
        $builderMock->shouldReceive('build')->once()->andReturn($mock);
    
        return $builderMock;
    });