PHPackages                             ecomdev/magento2-test-essentials - PHPackages - PHPackages  [Skip to content](#main-content)[PHPackages](/)[Directory](/)[Categories](/categories)[Trending](/trending)[Leaderboard](/leaderboard)[Changelog](/changelog)[Analyze](/analyze)[Collections](/collections)[Log in](/login)[Sign up](/register)

1. [Directory](/)
2. /
3. [Testing &amp; Quality](/categories/testing)
4. /
5. ecomdev/magento2-test-essentials

ActiveLibrary[Testing &amp; Quality](/categories/testing)

ecomdev/magento2-test-essentials
================================

Magento 2 Test Essentials

v1.0.0(1y ago)1815041MITPHPPHP ~8.1.0||~8.2.0||~8.3.0

Since Jan 14Pushed 1y ago1 watchersCompare

[ Source](https://github.com/EcomDev/magento2-test-essentials)[ Packagist](https://packagist.org/packages/ecomdev/magento2-test-essentials)[ RSS](/packages/ecomdev-magento2-test-essentials/feed)WikiDiscussions main Synced 1w ago

READMEChangelog (1)Dependencies (9)Versions (3)Used By (1)

🎯 Essentials for testing Magento 2 modules
==========================================

[](#-essentials-for-testing-magento-2-modules)

[![PHP Package](https://github.com/EcomDev/magento2-test-essentials/actions/workflows/php-package.yml/badge.svg)](https://github.com/EcomDev/magento2-test-essentials/actions/workflows/php-package.yml)

Using mocking frameworks for testing Magento 2 modules is counterproductive as you replicate line by line your actual calls to a magento implementation.

Binding your tests to the details of implementation leads to very fragile test suite that no-one wants to work with afterwards as a small change in underlying code like extraction of the class requires complete rewrite of the test case.

This package solves this problem by providing `fake objects` for most common operations you might want to interact with core.

As well as set of fake objects there is an `ObjectManagerInterface` implementation that automatically instantiates dependencies if you use `create` method and allows specifying custom factories for creation of deep dependency.

Each fake object is covered by automated tests to make sure that behaviour is correct your tests can test your code specific behaviour by using different scenarios.

📦 Installation
--------------

[](#-installation)

```
composer require --dev ecomdev/magento2-test-essentials
```

For database based tests it is recommended also to install collection of [testcontainers](https://github.com/EcomDev/testcontainer-magento-data):

```
composer require --dev ecomdev/testcontainers-magento-data
```

Examples
--------

[](#examples)

### Testing Class with Store and Configuration

[](#testing-class-with-store-and-configuration)

Imagine we have class that depending on current store configuration value view returns different values Usually you would mock every dependency call in it, which is error-prone as you never with dependency behaviour.

**YourService.php**

```
use Magento\Store\Model\StoreManagerInterface;
use Magento\Store\Model\ScopeInterface;
use Magento\Framework\App\Config\ScopeConfigInterface;
use Magento\Catalog\Model\Product;

class YourService
{
    private $storeManager;

    public function __construct(
        private readonly StoreManagerInterface $storeManager,
        private readonly ScopeConfigInterface $scopeConfig
    )
    {
    }

    public function applyCurrentStoreToProduct(Product $product)
    {
        $currentStore = $this->storeManager->getStore();

        if ($aliasStore = $this->scopeConfig->getValue(
                'catalog/product/store_alias',
                ScopeInterface::SCOPE_STORE,
                $currentStore->getCode()
            )) {
            $product->setStoreId($this->storeManager->getStore($aliasStore)->getId());
        }
    }
}
```

**YourServiceTest.php**

```
use PHPUnit\Framework\TestCase;
use PHPUnit\Framework\Attributes\Test;
use EcomDev\Magento2TestEssentials\ScopeConfig;
use EcomDev\Magento2TestEssentials\Store\StoreManager;
use EcomDev\Magento2TestEssentials\ObjectManager;
use Magento\Catalog\Block\Product;

class YourServiceTest extends TestCase
{
    private ObjectManager $objectManager;

    protected function setUp() : void
    {
        $this->objectManager =  ObjectManager::new()
            ->withObject(StoreManager::class, StoreManager::new()
                ->withStore(Store::new(3, 'store_three'))
                ->withStore(Store::new(1, 'store_one'))
                ->setCurrentStore('store_three'))
            ->withFactory(ScopeConfig::class, static ($objectManager) => ScopeConfig::new()
                ->withStoreManager($objectManager->get(StoreManager::class))
                ->withStoreValue('store_three', 'catalog/product/store_alias', 1));
    }

    #[Test]
    public function appliesStoreIdToProductWhenFlagIsSet()
    {
        $service = new YourService(
            $this->objectManager->get(StoreManager::class),
            $this->objectManager->get(ScopeConfig::class)
        );

        // Creates product without any constructor
        // but if you rely on data fields, it works great
        $product = $this->objectManager->get(Product::class);

        $service->applyCurrentStoreToProduct(
            $product
        );

        $this->assertEquals(1, $product->getStoreId());
    }

    #[Test]
    public function keepsOriginalStoreId()
    {
        $service = new YourService(
            $this->objectManager->get(StoreManager::class)
                ->setCurrentStore(1),
            $this->objectManager->get(ScopeConfig::class)
        );

        $product = $this->objectManager->get(Product::class);

        $service->applyCurrentStoreToProduct(
            $product
        );

        $this->assertEquals(null, $product->getStoreId());
    }
}
```

### Easy Real Database Integration Testing

[](#easy-real-database-integration-testing)

In combination with magento data [testcontainers](https://github.com/EcomDev/testcontainer-magento-data-php) it is possible to write quick integration tests

Imagine your service depends on Magento's `ResourceConnection` which is almost impossible to instantiate without installing whole Magento app:

```
use Magento\Framework\App\ResourceConnection;

class SomeSimpleService
{
    public function __construct(private readonly ResourceConnection $resourceConnection)
    {
    }

    public function totalNumberOfSimpleProducts(): int
    {
        $connection = $this->resourceConnection->getConnection();
        $select = $connection->select()
            ->from(
                $this->resourceConnection->getTableName('catalog_product_entity'),
                 ['count' => 'COUNT(*)']
             )
            ->where('type_id = ?', 'simple')

        return (int)$connection->fetchOne($select);
    }
}
```

Now you can create all the required dependencies with the help of `IntegrationUtility` by specifying connection details:

```
use EcomDev\TestContainers\MagentoData\DbConnectionSettings;
use EcomDev\TestContainers\MagentoData\DbContainerBuilder;
use Magento\Framework\App\ResourceConnection;
use PHPUnit\Framework\Attributes\Test;
use PHPUnit\Framework\TestCase;

class IntegrationUtilityTest extends TestCase
{
    #[Test]
    public function returnsCorrectAmountOfSimpleProductsInSampleDataDb()
    {
        $container = DbContainerBuilder::mysql()
            ->withSampleData()
            ->build();

        $connectionSettings = $container->getConnectionSettings();

        $objectManager = IntegrationUtility::setupDatabaseObjects(
            DeploymentConfig::new()
                ->withDatabaseConnection(
                    $connectionSettings->host,
                    $connectionSettings->user,
                    $connectionSettings->password,
                    $connectionSettings->database
                )
        );

        $service = $objectManager->get(SomeSimpleService::class);

        $this->assertEquals(
            1891,
            $service->totalNumberOfSimpleProducts()
        );
    }
}
```

Now there is no excuse to not write tests for your database components!

✨ Features
----------

[](#-features)

- `ObjectManagerInterface` implementation which mimics platform's behaviour
- `StoreInterface` implementation as a simple data object for testing store related behaviour
- `GroupInterface` implementation as a simple data object for testing store group related behaviour
- `WebsiteInterface` implementation as a simple data object for testing website related behaviour
- `ScopeConfigurationInterface` implementation for testing configuration dependent functionality
- `DeploymentConfig` implementation for using in configuration caches, db connections, http cache, etc
- `ResourceConnection` implementation for quick testing of database components

📜 License
---------

[](#-license)

This project is licensed under the MIT License. See the [LICENSE](LICENSE) file for more details.

###  Health Score

35

—

LowBetter than 80% of packages

Maintenance41

Moderate activity, may be stable

Popularity22

Limited adoption so far

Community15

Small or concentrated contributor base

Maturity54

Maturing project, gaining track record

 Bus Factor1

Top contributor holds 92% of commits — single point of failure

How is this calculated?**Maintenance (25%)** — Last commit recency, latest release date, and issue-to-star ratio. Uses a 2-year decay window.

**Popularity (30%)** — Total and monthly downloads, GitHub stars, and forks. Logarithmic scaling prevents top-heavy scores.

**Community (15%)** — Contributors, dependents, forks, watchers, and maintainers. Measures real ecosystem engagement.

**Maturity (30%)** — Project age, version count, PHP version support, and release stability.

###  Release Activity

Cadence

Unknown

Total

1

Last Release

488d ago

### Community

Maintainers

![](https://www.gravatar.com/avatar/190d12eae43e0d874394cbc7fc49ea94c6b6e1bc8b05f75b94fbd0b9c4b5d15f?d=identicon)[IvanChepurnyi](/maintainers/IvanChepurnyi)

---

Top Contributors

[![IvanChepurnyi](https://avatars.githubusercontent.com/u/866758?v=4)](https://github.com/IvanChepurnyi "IvanChepurnyi (23 commits)")[![github-actions[bot]](https://avatars.githubusercontent.com/in/15368?v=4)](https://github.com/github-actions[bot] "github-actions[bot] (1 commits)")[![lucafuser](https://avatars.githubusercontent.com/u/46565169?v=4)](https://github.com/lucafuser "lucafuser (1 commits)")

---

Tags

testingmagento2fake objects

###  Code Quality

TestsPHPUnit

Code StylePHP\_CodeSniffer

### Embed Badge

![Health badge](/badges/ecomdev-magento2-test-essentials/health.svg)

```
[![Health](https://phpackages.com/badges/ecomdev-magento2-test-essentials/health.svg)](https://phpackages.com/packages/ecomdev-magento2-test-essentials)
```

###  Alternatives

[mollie/magento2

Mollie Payment Module for Magento 2

1121.6M10](/packages/mollie-magento2)[smile/elasticsuite

Magento 2 merchandising and search engine built on ElasticSearch

8044.5M33](/packages/smile-elasticsuite)[dotdigital/dotdigital-magento2-extension

Dotdigital for Magento 2

50374.2k18](/packages/dotdigital-dotdigital-magento2-extension)[swissup/module-search-mysql-legacy

Legacy mysql search for magento 2.4

10483.0k](/packages/swissup-module-search-mysql-legacy)[opengento/module-category-import-export

This module add the capability to import and export the categories from the back-office.

119.1k](/packages/opengento-module-category-import-export)[mage-os/module-inventory-reservations-grid

Add a grid with the list of inventory reservations.

126.8k](/packages/mage-os-module-inventory-reservations-grid)

PHPackages © 2026

[Directory](/)[Categories](/categories)[Trending](/trending)[Changelog](/changelog)[Analyze](/analyze)
