繁体   English   中英

如何在 magento 2 phpunit 测试中进行依赖注入

[英]How to do dependency injection in magento 2 phpunit tests

我将我的配置存储在 env.php 中,所以我需要在我的测试类中使用依赖注入来访问配置。 所以我想了解如何在我的测试类中注入配置类“Magento\\Framework\\App\\DeploymentConfig”。

我尝试使用构造函数和 objectManager,但似乎无法让它工作

第一次尝试

    {
        //$objectManager = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this);
        $objectManager = \Magento\Framework\App\ObjectManager::getInstance();
        $config = $objectManager->get('Magento\Framework\App\DeploymentConfig');
        $test_config = $config->get('tests');

        // create our http client (Guzzle)
        $this->client = new Client(['base_uri' => $test_config['base_url']]);
        //set headers
        $this->headers = [
            'Authorization' => 'Bearer ' . $test_config['token'],
            'Accept'        => 'application/json',
            'Content-Type'  => 'application/json',
        ];
    }

第二次尝试

public function __construct(
     \Magento\Framework\App\DeploymentConfig $config
) {
     $this->test_config = $config->get('tests');   
}

    public function Setup()
    {
        $objectManager = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this);
        $config = $objectManager->getObject('Magento\Framework\App\DeploymentConfig');
        $test_config = $config->get('tests');

        // create our http client (Guzzle)
        $this->client = new Client(['base_uri' => $test_config['base_url']]);
        //set headers
        $this->headers = [
            'Authorization' => 'Bearer ' . $test_config['token'],
            'Accept'        => 'application/json',
            'Content-Type'  => 'application/json',
        ];
    }

我认为您正在尝试在测试用例中调用 API。

PHP 单元测试用例不会调用实际的 API,您需要在willReturn方法中传递该 API 调用的返回值。

请查看下面给出的示例。

在类似的情况下,我使用了以下代码。

$this->scopeConfig = $this->getMockBuilder(Magento\Framework\App\Config\ScopeConfigInterface::class)
            ->setMethods(['getValue'])
            ->disableOriginalConstructor()
            ->getMockForAbstractClass();

$this->scopeConfig->expects($this->any())
            ->method('getValue')->willReturn('your config value');

如果您的代码有多个getValue调用实例,请使用下面给出的代码。

$scopeConfigInterface = $this->createMock(Magento\Framework\App\Config\ScopeConfigInterface::class);

        $valueMap = [
            ['<SECTION NAME>/<GROUP NAME>/<FIELD NAME>', \Magento\Store\Model\ScopeInterface::SCOPE_STORE, null, '<CONFIG VALUE>']
        ];
        $scopeConfigInterface->method('getValue')->willReturnMap($valueMap);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM