簡體   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