A guide to utilizing dependency injection in phpunit tests for Magento 2

I've been utilizing env.php to store my configurations, which is why I'm looking to implement dependency injection in my test class in order to access the configs. How can I inject the config class 'Magento\Framework\App\DeploymentConfig' into my test class?

I've attempted using both the constructor and the objectManager but so far have not been successful.

Initial approach:


{
    //$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',
    ];
}

Second try:


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',
    ];
}

Answer №1

It seems like you are attempting to make an API call within your test case.

When using PHP unit for testing, the test case won't actually make the API call. Instead, you should provide the expected return value of the API call using the willReturn method.

Take a look at the examples below for guidance.

In a similar situation, I utilized the following code snippet:

$this->apiManager = $this->getMockBuilder(App\API\ManagerInterface::class)
            ->setMethods(['callAPI'])
            ->disableOriginalConstructor()
            ->getMockForAbstractClass();

$this->apiManager->expects($this->any())
            ->method('callAPI')->willReturn('expected API response');

If your code requires multiple calls of the callAPI method, consider using this code snippet:

$apiInterface = $this->createMock(App\API\ManagerInterface::class);

        $returnValues = [
            ['endpoint1', 'param1', 'result1'],
            ['endpoint2', 'param2', 'result2']
        ];
        $apiInterface->method('callAPI')->willReturnMap($returnValues);

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

When using jQuery and AJAX, the functions each, if, post, and .html work properly but occasionally erase data inexplicably

I have a PHP page containing FedEx and UPS tracking numbers stored in a MySQL database, which are displayed within DIVs with the class "trackingnumber". Using JavaScript, I loop through these divs to retrieve the ID and then send it to a PHP page that fetc ...

Error message "Authorization issue occurred while trying to call a function in the PHP webservice."

I am facing an issue with calling a web service. It successfully connects and returns its methods, however, when I call one of the functions, it throws an unauthorized error. Here is my code try { $service = new SoapClient("http://www.go-to-orbit.com/oo ...

PHP Prepared Statements with MySQLi: Slow Retrieval of Blob Field

To enhance security measures, I have incorporated a function that handles prepared statements. However, an issue has arisen when attempting to retrieve base64 encoded blob data (approximately 30-50KB) through this method. Unsurprisingly, executing the qu ...

SQL statement not recognized

My current project involves conducting an experiment using a pre-coded script accessible through the link here. In this experiment, I'm utilizing xampp as my web server with mysql. However, when I attempt to run the authentication page containing the ...

Handling error reporting using JSON in jQuery AJAX post success

UPDATE: I have resolved the PHP errors mentioned in previous Answers, however, the issue still persists. I am attempting to implement an error message display in case of a failed POST request and a success message for successfully completed requests. Curr ...

What is the best way to retrieve a PHP response using jQuery's .load method

Here are some sample codes for better understanding. This code is from my file named some3.php: <head> <script src="jquery-1.7.2.js" type="text/javascript"></script> <script type="text/javascript"> $(document).ready(function(){ ...

Redirecting in Laravel after making an AJAX request results in a "Method Not Allowed" error

I've encountered an unusual problem with my web application built using Vue 3 and Inertia, which includes forms. So, here's the scenario: If I have two browsers open and log out in one, then trigger an Ajax request in the other, it goes through t ...

"Check the position of the value in the if statement

Can you explain the distinction between these two statements: if (false === $variable) { //do something } and if ($variable === false) { //do something } I typically prefer the second format, but have noticed that many frameworks I work with use th ...

Utilizing Bootstrap Modal to Display PHP Data Dynamically

Modals always pose a challenge for me, especially when I'm trying to work with someone else's code that has a unique take on modals that I really appreciate (if only I can make it function correctly). The issue arises when the modal is supposed ...

What is the method for determining the PHP version linked to a specific version of XAMPP on Windows 10 without the need for installation?

Looking to set up magento2.3 on localhost windows? Make sure you have one of the following versions of php available: ~5.6.5|7.0.2|7.0.4|~7.0.6|~7.1.0 . Unfortunately, these specific versions are not included in the latest release of xampp. Instead of tr ...

Retrieve the names from one table by querying another table

I am working with a database that consists of 3 tables: Categories, Subcategories, and Articles. Within my Articles table, I have columns labeled CategoryID and SubcategoryID, both of which are foreign keys referencing the Categories and Subcategories tabl ...

PHP construction does not seem to be functioning properly as it is displaying a blank page

I have created a PHP class file, but when I try to run it, it does not work. class User { public function __construct(){ $host_name='localhost'; $username='root'; $password=''; $database_name='php&apos ...

Failed to save information in JSON format

I'm currently facing an issue with JSON while trying to implement a register and login feature. The data fails to be stored as intended. Here is the JSON response I am receiving in the log: 02-24 08:24:47.878: E/JSON(2017): {"tag":"register","success ...

Switching from HTML to PHP redirection

I'm encountering an issue with my PHP and HTML setup. I want to create a link that redirects to a PHP page containing a login form. Here's the code snippet I've used: <p><a href="LoginPage.php">Login</a></p> However ...

A simple trick I use to eliminate the line breaks in sentences is by removing the ret

These are the sentences I have: DEssus 3 Liasee Dessous Is there a way to create a function that will keep the sentence on one line? Output : DEssus 3 Liasse Dessous ...

How can I use CURL in PHP to read a JSON URL?

Similar Query: Retrieve the value of a URL response using curl I am working with a JSON URL as shown below www.example.com/hello.php?action=get&id=18&format=json This URL will return the following output: {"id":18,"name":"Dharma"}. Could so ...

Eliminate redundant information from loop in PHP

Can anyone assist me in resolving this issue? I am attempting to display 3 text fields containing the following values: 100 200 300 However, my current output is showing duplicates: 100,200,300 100,200,300 100,200,300 I have tried using the arra ...

What could be causing disparities in the padding of certain table cells compared to others?

If you're interested, I created a photo gallery over at Take a look around and feel free to download any wallpapers that catch your eye! The issue I'm encountering is with the padding of the columns - specifically, the first and last columns ha ...

Using PHP's explode function to parse data from a text file

The issue occurs with PHP when using an included txt file where the explode function fails. The content of the txt file is simply: a,b,c,d,e. However, when not using an include statement, the string successfully 'explodes' into an array. $data = ...

Withdrawal of answer from AJAX request

Is there a way to create a function that specifically removes the response from an AJAX call that is added to the inner HTML of an ID? function remove_chat_response(name){ var name = name; $.ajax({ type: 'post', url: 'removechat.php ...