小编abr*_*low的帖子

如何在功能测试中使用symfony 4模拟服务?

我有一个Commandbus处理程序,它注入了一些服务:

class SomeHandler
{
    private $service;

    public function __construct(SomeService $service)
    {
        $this->service = $service;
    }

    public test(CommandTest $command)
    {
        $this->service->doSomeStuff();
    }
}
Run Code Online (Sandbox Code Playgroud)

SomeService的方法doSomeStuff具有外部调用,我不想在测试期间使用它。

class SomeService
{
    private $someBindedVariable;

    public function __construct($someBindedVariable)
    {
        $this->someBindedVariable = $someBindedVariable;
    }

    public function doSomeStuff()
    {
        //TODO: some stuff
    }
}
Run Code Online (Sandbox Code Playgroud)

在测试中,我尝试用模拟对象替换服务

public function testTest()
{
    $someService = $this->getMockBuilder(SomeService::class)->getMock();
    $this->getContainer()->set(SomeService::class, $someService);

    //TODO: functional test for the route, which uses SomeHandler
}
Run Code Online (Sandbox Code Playgroud)

第一个问题是该代码将引发异常““ App \ Service \ SomeService”服务是私有的,您无法替换它。”

好的,让我们尝试将其公开:

services.yaml:

App\Service\SomeService:
    public: true
    arguments:
        $someBindedVariable: 200
Run Code Online (Sandbox Code Playgroud)

但这没有帮助。我从本地SomeService得到响应。让我们尝试使用别名: …

service dependency-injection functional-testing symfony

6
推荐指数
2
解决办法
2023
查看次数