首页  >  问答  >  正文

在 Laravel 9.x 中使用部分模拟时出现问题

<p>嘿,laravel 开发人员,我发现了部分模拟的问题,我需要测试一个使用内部方法的方法,这需要被模拟,我尝试使用几种方法来模拟该方法,例如下一个想法:</p> <pre class="brush:php;toolbar:false;">#1 $mockMyClass = Mockery::mock( $myClassInstance )->makePartial(); #2 $mockMyClass = $this->partialMock(); #3 $mockMyClass = $this->createPartialMock(); // and then $mockMyClass->shouldReceive('internalMethod') ->andReturn($responseInternalMethod);</pre> <p>并且显然使用文档 Laravel Mocking Objects 中描述的方式</p> <pre class="brush:php;toolbar:false;">use App\Service; use Mockery\MockInterface; $mock = $this->partialMock(Service::class, function (MockInterface $mock) { $mock->shouldReceive('process')->once(); });</pre> <p>这些想法都行不通,$mockMyClass 总是执行真正的方法,而不是应该返回 $responseInternalMethod 的模拟方法。有人也有这个问题吗?我需要确认是否是 Laravel、Mockito 或外部的问题,而不是本地环境问题,哈哈。我读懂了你们!</p> <p>技术细节: Laravel 9.x PHP 8.1 PHP 单元 9.5 嘲讽1.5</p>
P粉726234648P粉726234648385 天前483

全部回复(1)我来回复

  • P粉885035114

    P粉8850351142023-09-03 17:16:49

    好吧,我找到了解决方案,但无论如何,我有兴趣知道是否有人也遇到这个问题

    我解决这个问题的方法是:

    public function testRealExternalMethod()
    {
        // Create a mock of the dependency that will be used by the class
        $mockDependency = $this->createMock(Dependency::class);
        
        // in this case we need to use a partial mock because we have an internal method
        $mockMyClass = Mockery::mock(
            MyClass::class,
            [$mockDependency, $parameter1]
        )
            ->makePartial();
    
        $responseInternalMethod = ['needed data'];
    
        $mockMyClass->shouldReceive('internalMethod')
            ->andReturn($responseInternalMethod);
    
        $result = $mockMyClass->realExternalMethod($parameter2, $parameter3);
    }
    这些情况的解决方案是直接创建我的类的模拟实例,并将构造函数所需的所有参数作为依赖项或数据。然后使用模拟类作为真实类继续测试循环。

    回复
    0
  • 取消回复