Symfony 4.1:如何在 UnitTest 中使用依赖注入 (Swift_Mailer)

5 phpunit unit-testing swiftmailer symfony symfony4

在我的 Symfony4.1-项目中,我试图测试一种方法,该方法应该通过单元测试使用 SwiftMailer 发送邮件。

我的测试课看起来像这样

namespace App\Tests;

use App\Controller\UserImageValidationController;
use Symfony\Bundle\FrameworkBundle\Tests\TestCase;

class UserImageValidationControllerTest extends TestCase
{

    private $mailer = null;
    public function __construct(\Swift_Mailer $testmySwiftMailer)
    {
        $this->mailer = $testmySwiftMailer;
    }

    public function testMail()
    {
        $controller = new UserImageValidationController();

        $controller->notifyOfMissingImage(
            'a',
            'b',
            'c',
            'd',
            $this->mailer
        );
    }
}
Run Code Online (Sandbox Code Playgroud)

问题是,当我运行时./bin/phpunit出现异常

未捕获的 ArgumentCountError:函数 App\Tests\UserImageValidationControllerTest::__construct() 的参数太少,0 [...] 且恰好 1 个预期 [...]

看起来在测试环境中 DI 不起作用。

所以我添加了

bind:
    $testmySwiftMailer: '@swiftmailer.mailer.default'
Run Code Online (Sandbox Code Playgroud)

对于我的config/services_test.yaml但我仍然遇到相同的错误。我还添加autowiring: true到该文件(只是为了尝试),但它也不起作用。另外,我尝试使用服务别名,就像文件注释中所述:仍然没有成功。

如何将 swiftmailer 注入到我的测试用例构造函数中?

Jor*_*rge 3

测试不是容器的一部分,也不充当服务,因此您的解决方案无效。扩展Symfony\Bundle\FrameworkBundle\Test\KernelTestCase并执行此操作(首先确保您的服务是公开的):

protected function setUp()
{
    static::bootKernel();

    $this->mailer = static::$kernel->getContainer()->get('mailer');
}

protected function tearDown()
{
    $this->mailer = null;
}
Run Code Online (Sandbox Code Playgroud)

  • 这里解释得很好https://symfony.com/blog/new-in-symfony-4-1-simpler-service-testing (2认同)