API Functional Testing in Magento 2

If you have created an API and want to write test files for that API, but have no idea about how it can be done in Magento 2. This post is for you.

The Web API testing framework enables you to test Magento Web API from the viewpoint of the client application. These tests can be applied with both REST or SOAP. The REST or SOAP adapter which runs the tests will be specified in PHPUnit configuration.

In today post, I am going to provide you various information about API Functional Testing

Main contents

Magento API Integration Service by Mageplaza

Connect your store with any 3rd-party software and boost customer experience quickly and efficiently.

Learn more
Magento API Integration service

Implementation Details

The Web API functional testing framework based on the integration testing framework. Also, most of the classes implemented there are reused by it.

Custom Annotations for Data Fixtures

Only in the Web API functional tests, the custom annotation, which is @magentoApiDataFixture is available for declaring fixtures. The difference between this and @magentoDataFixture is that during HTTP requests which are made within the test body, the fixture will be committed and accessible. The usage rules of @magentoApiDataFixture and @magentoDataFixture are the same.

Note: If the @magentoApiDataFixture is used to add a date to the DB, that data will not be auto-cleared after test execution. Instead, it will be cleared when you use @magentoDataFixture.

The fixtures must not be defined in dev/tests/api-functional, instead, they have to be taken from dev/tests/integration. Most necessary fixtures are defined by the integration framework. And during Web API functional testing, they should be reused. If the existing fixtures set is insufficient, new fixtures are added under dev/tests/integration. As a result, the fixtures will be available for both testing frameworks.

After test execution, remember to clear all entities which are created in fixture files or within tests itself from the DB. This would ensure the test environment is clean. You can do this directly in tearDown or by a corresponding rollback for the fixture file. The file name should be similar to a fixture, but with _rollback suffix.

Create a New Test

All Web API functional tests need to inherit from the generic test case Magento\TestFramework\TestCase\WebapiAbstract. The _webApiCall() method is defined, and be used to perform Web API calls from tests. _webApiCall() clients are unaware of which adapter will be used to display the remote call.

namespace Magento\Webapi\Routing;

class CoreRoutingTest extends \Magento\TestFramework\TestCase\WebapiAbstract
{
    public function testBasicRoutingExplicitPath()
    {
        $itemId = 1;
        $serviceInfo = [
            'rest' => [
                'resourcePath' => '/V1/testmodule1/' . $itemId,
                'httpMethod' => \Magento\Framework\Webapi\Rest\Request::HTTP_METHOD_GET,
            ],
            'soap' => [
                'service' => 'testModule1AllSoapAndRestV1',
                'operation' => 'testModule1AllSoapAndRestV1Item',
            ],
        ];
        $requestData = ['itemId' => $itemId];
        $item = $this->_webApiCall($serviceInfo, $requestData);
        $this->assertEquals('testProduct1', $item['name'], "Item was retrieved unsuccessfully");
    }
}

The above test is used to test SOAP and REST based on the adapter which the testing framework currently use. The $serviceInfo format is defined by the Web API client adapter interface:

namespace Magento\TestFramework\TestCase\Webapi;

interface AdapterInterface
{
    /**
     * Perform call to the specified service method.
     *
     * @param array $serviceInfo <pre>
     * array(
     *     'rest' => array(
     *         'resourcePath' => $resourcePath, // e.g. /products/:id
     *         'httpMethod' => $httpMethod,     // e.g. GET
     *         'token' => '21hasbtlaqy8t3mj73kjh71cxxkqj4aq'    // optional : for token based Authentication. Will
     *                                                             override default OAuth based authentication provided
     *                                                             by test framework
     *     ),
     *     'soap' => array(
     *         'service' => $soapService,    // soap service name with Version suffix e.g. catalogProductV1, customerV2
     *         'operation' => $operation     // soap operation name e.g. catalogProductCreate
     *     )
     * );
     * </pre>
     * @param array $arguments
     * @param string|null $storeCode if store code not provided, default store code will be used
     * @param \Magento\Integration\Model\Integration|null $integration
     * @return array|string|int|float|bool
     */
    public function call($serviceInfo, $arguments = [], $storeCode = null, $integration = null);
}

Run the Tests

Prerequisites

  1. Firstly, you need to install the PHP Soap extension.

In order to do that, you need to copy php_soap.dll or php_soap.so to your PHP extensions directory. Then, edit your php.ini file and turn on the PHP Soap extension, which means deleting the leading semi-colon that is in front of the extension. Next, restart Apache.

extension=php_soap.dll
  1. Before functional tests are ready to be run, you need to clear your cache.

Running the Tests

  1. Firstly, copy /dev/tests/api-functional/phpunit_rest.xml.dist and phpunit_soap.xml.dist to the files /dev/tests/api-functional/phpunit_rest.xml and phpunit_soap.xml.
  2. The Magento instance URL has to be defined as a value of TESTS_BASE_URL, Test Webservice User as the value of TESTS_WEBSERVICE_USER and Test Webservice API key as the value of TESTS_WEBSERVICE_APIKEY in the copied file, for example, phpunit_rest.xml or phpunit_soap.xml.
  3. /dev/tests/api-functional/config/install-config-mysql.php.dist need to be copied to /dev/tests/api-functional/config/install-config-mysql.php.
  4. Then, your DB connection needs to be configured and the setting need to installed in the file /dev/tests/api-functional/config/install-config-mysql.php. The Magento database is specified. You must specify the base URL to access this Magento instance in a copied file such as phpunit_rest.xml or phpunit_soap.xml.
  5. Finally, use the configuration file /dev/tests/api-functional/phpunit_rest.xml or /dev/tests/api-functional/phpunit_soap.xml to run phpunit.

Conclusion

Above, I have just provided you various information about API Functional Testing in Magento 2 including the implementation details, how to create a new test, and also how to run the tests. Hope this article is useful for you. If you have any questions or new ideas, feel free to leave a comment below.

Thank you for reading!

x