how to set up and write integration tests

Hi Guys, Today we are going to talk about how to setup and write Integration Tests in Magento 2. As you might know you can write your integration tests for any part of your module for example Block, Controller, Console, Cron, Model, Observer, Plugin, Setup, UI etc. Before we start, we are going to outline the key function of integration test classes with brief explanation.

setUpBeforeClass– This is called once before running all tests in the class

tearDownAfterClass – This is called once after running all tests in the class

setUp – This is called before running a test in the class

tearDown – This is called before running a test in the class

To run all the integration tests for your whole instance you can use the following command

bin/magento dev:tests:run integration

To run all the integration tests for your specific module you can use the following command

php vendor/phpunit/phpunit/phpunit -c dev/tests/integration/phpunit.xml dev/tests/integration/testsuite/Magento/Catalog/

To run specific integration test you can use the following command

php vendor/phpunit/phpunit/phpunit -c dev/tests/unit/phpunit.xml.dist dev/tests/integration/testsuite/Magento/Catalog/Model/ProductTest.php

Please see the list of Integration Test functions which could be useful for your integration testing

AssertTrue/AssertFalse – Check the input to verify it equals true/false

AssertEquals – Check the result against another input for a match

AssertGreaterThan – Check the result to see if it’s larger than a value (there’s also LessThan, GreaterThanOrEqual, and LessThanOrEqual)

AssertContains – Check that the input contains a certain value

AssertType – Check that a variable is of a certain type

AssertNull – Check that a variable is null

AssertFileExists – Verify that a file exists

AssertRegExp – Check the input against a regular expression

Set Up Integration Tests for Magento 2

Step 1 – Create a new empty database for example “magento_integration_tests” using the following command

CREATE DATABASE magento_integration_tests;
GRANT ALL ON magento_integration_tests.* TO 'root'@'localhost' IDENTIFIED BY '123123q';

Step 2 – Copy the file dev/tests/integration/phpunit.xml.dist to dev/tests/integration/phpunit.xml and you can change it to run only your custom integration tests on your local by changing the following information in the file -:

<!-- Test suites definition --> <testsuites> <!-- Memory tests run first to prevent influence of other tests on accuracy of memory measurements --> <!--testsuite name="Memory Usage Tests"> <file>testsuite/Magento/MemoryUsageTest.php</file> </testsuite> <testsuite name="Magento Integration Tests"> <directory suffix="Test.php">testsuite</directory> <exclude>testsuite/Magento/MemoryUsageTest.php</exclude> </testsuite--> <testsuite name="Scommerce"> <directory suffix="Test.php">app/code/Scommerce/*/Test/Integration</directory> </testsuite> </testsuites>

Step 3 – Copy the file dev/tests/integration/install-config-mysql.php.dist to dev/tests/integration/install-config-mysql.php and change the information based on Step 1

 return [ 'db-host' => 'localhost', 'db-user' => 'root', 'db-password' => '123123q', 'db-name' => 'magento_integration_tests', 'db-prefix' => '', 'backend-frontname' => 'backend', 'admin-user' => MagentoTestFrameworkBootstrap::ADMIN_NAME, 'admin-password' => MagentoTestFrameworkBootstrap::ADMIN_PASSWORD, 'admin-email' => MagentoTestFrameworkBootstrap::ADMIN_EMAIL, 'admin-firstname' => MagentoTestFrameworkBootstrap::ADMIN_FIRSTNAME, 'admin-lastname' => MagentoTestFrameworkBootstrap::ADMIN_LASTNAME,

Now your integration setup is in place, let’s crack on with writing our first integration tests

Step 1 – Create your fixture file, this file will create the data which will be required to run your tests under ScommerceCustomTestIntegration_filesproducts.php

use MagentoTestFrameworkHelperBootstrap; /** @var $product MagentoCatalogModelProduct */
$product = Bootstrap::getObjectManager() ->create(MagentoCatalogModelProduct::class);
$product ->setTypeId('simple') ->setId(1) ->setAttributeSetId(4) ->setWebsiteIds([1]) ->setName('Simple Product') ->setSku('simple') ->setPrice(10) ->setMetaTitle('meta title') ->setMetaKeyword('meta keyword') ->setMetaDescription('meta description') ->setVisibility(MagentoCatalogModelProductVisibility::VISIBILITY_BOTH) ->setStatus(MagentoCatalogModelProductAttributeSourceStatus::STATUS_ENABLED) ->setStockData(['use_config_manage_stock' => 0]) ->save(); $customDesignProduct = Bootstrap::getObjectManager() ->create(MagentoCatalogModelProduct::class, ['data' => $product->getData()]); $customDesignProduct->setUrlKey('custom-design-simple-product') ->setId(2) ->setRowId(2) ->setSku('custom-design-simple-product') ->setCustomDesign('Magento/blank') ->save(); 

Step 2 – Create your integration test file which will run your test and confirm if data created in Step 1 matches what is expected on the frontend

 namespace ScommerceCustomTestIntegrationController; /** * @magentoAppIsolation enabled */
class ProductTest extends MagentoTestFrameworkTestCaseAbstractController
{ /** * @magentoDataFixture Scommerce/Catalog/controllers/_files/products.php * @magentoAppArea frontend */ public function testViewAction() { /** @var $objectManager MagentoTestFrameworkObjectManager */ $objectManager = MagentoTestFrameworkHelperBootstrap::getObjectManager(); /** * @var $repository MagentoCatalogModelProductRepository */ $repository = $objectManager->create('MagentoCatalogModelProductRepository'); $product = $repository->get('simple_product_1'); $this->dispatch(sprintf('catalog/product/view/id/%s', $product->getEntityId())); /** @var $currentProduct MagentoCatalogModelProduct */ $currentProduct = $objectManager->get('MagentoFrameworkRegistry')->registry('current_product'); $this->assertInstanceOf('MagentoCatalogModelProduct', $currentProduct); $this->assertEquals($product->getEntityId(), $currentProduct->getEntityId()); $lastViewedProductId = MagentoTestFrameworkHelperBootstrap::getObjectManager()->get( 'MagentoCatalogModelSession' )->getLastViewedProductId(); $this->assertEquals($product->getEntityId(), $lastViewedProductId); $responseBody = $this->getResponse()->getBody(); /* Product info */ $this->assertContains('Simple Product 1 Name', $responseBody); $this->assertContains('Simple Product 1 Full Description', $responseBody); $this->assertContains('Simple Product 1 Short Description', $responseBody); /* Stock info */ $this->assertContains('$1,234.56', $responseBody); $this->assertContains('In stock', $responseBody); $this->assertContains('Add to Cart', $responseBody); /* Meta info */ $this->assertContains('<title>Simple Product 1 Meta Title</title>', $responseBody); $this->assertSelectCount('meta[name="keywords"][content="Simple Product 1 Meta Keyword"]', 1, $responseBody); $this->assertSelectCount( 'meta[name="description"][content="Simple Product 1 Meta Description"]', 1, $responseBody ); }

Step 3 – Run your test using the following command -:

php vendor/phpunit/phpunit/phpunit -c dev/tests/integration/phpunit.xml app/code/Scommerce/Custom/Test/Integration/Controller/ProductTest.php

That’s it, Hope this article helped you in some way. Please leave us your comment and let us know what do you think? Thanks.

Similar Posts