Reputation: 349
I have developed some bundles, and I want to add tests for them. So, I have created the file Tests/Service/EmailServiceTest.php
that contains one test.
I have installed PHPUnit using sudo apt install phpunit
on my Ubuntu computer, but when I cd
to my bundle's folder and run phpunit
I have the following error:
c975L\EmailBundle\Tests\Service\EmailServiceTest::testCreateEmailObject Error: Class 'c975L\EmailBundle\Service\EmailService' not found
It looks like the autoloader can't find the class, even if declared at the top with use
.
How do we test a Symfony Bundle with PHPUnit?
Upvotes: 4
Views: 3565
Reputation: 8560
At present, there is no comprehensive and clear documentation on how to conduct functional tests for standalone Symfony bundles.
To gain insight into this, you can examine some Symfony bundles to understand their approaches:
https://github.com/lexik/LexikJWTAuthenticationBundle/tree/3.x/Tests
It is relative complicated and messy by my humble opinion.
Recently, Symfony released new conventions on how to write bundles. For example, the current recommendations suggest placing code in the 'src/' directory. However, all core Symfony bundles like "security bindle" still have code in the root, making everything even messier.
I wrote an article where I proposed my way how to do it with clean way:
https://medium.com/@fico7489/symfony-functional-tests-for-standalone-bundles-9666045a2309
Upvotes: 2
Reputation: 1029
It is a good idea to install phpunit on a per project basis, as version differences could come up if you have multiple projects.
(1) composer require phpunit/phpunit --dev
I saw some solutions over the web that requires to create a bootstrap.php with autoload but even with this, it doesn't work...
You can use composer's autoloader as a bootstrap. A custom bootstrap might come in handy in some cases, but not necessary.
(2) Create a phpunit.xml.dist
file, something like this (your current one does not specify a bootstrap):
<?xml version="1.0" encoding="UTF-8"?>
<phpunit bootstrap="./vendor/autoload.php">
<testsuites>
<testsuite name="MyBundle test suite">
<directory suffix="Test.php">./Tests</directory>
</testsuite>
</testsuites>
<filter>
<whitelist>
<directory>./</directory>
<exclude>
<directory>./Resources</directory>
<directory>./Tests</directory>
<directory>./vendor</directory>
</exclude>
</whitelist>
</filter>
</phpunit>
Also check out vendor/bin/phpunit --generate-configuration
which is nice.
(3) Run vendor/bin/phpunit
It should find the config file automatically, but you can also specify it with the --configuration
option
Upvotes: 3