gpt4 book ai didi

unit-testing - Symfony 4.1 : How to use Dependency Injection in UnitTest (Swift_Mailer)

转载 作者:行者123 更新时间:2023-12-04 14:23:31 25 4
gpt4 key购买 nike

在我的 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
);
}
}

问题是,当我运行 ./bin/phpunit我得到一个异常(exception)说

Uncaught ArgumentCountError: Too few arguments to function App\Tests\UserImageValidationControllerTest::__construct(), 0 [...] and exactly 1 expected [...]



似乎在测试环境中 DI 不起作用。

所以我补充说
bind:
$testmySwiftMailer: '@swiftmailer.mailer.default'

到我的 config/services_test.yaml 但我仍然遇到同样的错误。
我还加了 autowiring: true到该文件(只是为了尝试),它也不起作用。
此外,我尝试使用服务别名,就像文件评论中所说的那样:仍然没有成功。

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

最佳答案

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

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

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

protected function tearDown()
{
$this->mailer = null
}

关于unit-testing - Symfony 4.1 : How to use Dependency Injection in UnitTest (Swift_Mailer),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50858275/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com