Why Are Unit Tests Important in Shopware?
Unit tests help detect errors early and ensure a stable codebase. Especially for Shopware plugins, it is essential to verify functionality to prevent issues in live environments.
What Is a Unit Test?
A unit test checks the correctness of a single function or method without dependencies like databases or APIs.
Requirements for Unit Testing in Shopware
- 🔹 Installed PHPUnit (version 9.x or higher for PHP 8.3)
- 🔹 Shopware 6 development environment with Composer
- 🔹 Autoloading for test classes enabled (
composer dump-autoload
)
A Simple Unit Test Using PHPUnit
Example: A simple test for a Calculator
class.
namespace MyPlugin\Tests;
use PHPUnit\Framework\TestCase;
use MyPlugin\Service\Calculator;
class CalculatorTest extends TestCase {
public function testAddition() {
$calc = new Calculator();
$this->assertEquals(5, $calc->add(2, 3));
}
}
Unit Testing in Shopware: Testing a Service
Shopware uses dependency injection, meaning we can test services in isolation:
namespace MyPlugin\Tests;
use PHPUnit\Framework\TestCase;
use MyPlugin\Service\ProductService;
use Shopware\Core\Framework\Context;
class ProductServiceTest extends TestCase {
public function testGetProductName() {
$service = new ProductService();
$this->assertEquals('Product 1', $service->getProductName(1));
}
}
Mocking Shopware Dependencies
Using Mockery or PHPUnit mocks, we can simulate Shopware core classes:
$repoMock = $this->createMock(ProductRepository::class);
$repoMock->method('find')->willReturn(new Product('Test Product'));
Conclusion
Unit testing helps detect bugs early and increases the stability of Shopware plugins. It is an essential practice, especially for larger projects.
Need help setting up Unit Tests for your Shopware plugin? Contact me – I’d be happy to assist!