首页 > 解决方案 > 在表单(实体类型输入)上使用 Symfony4 进行的功能测试不起作用

问题描述

我有一个产品实体的表格

public function buildForm(FormBuilderInterface $builder, array $options)
{
    if ($options['edit'] === false) {
        $builder
            ->add('code', TextType::class, [
            'label' => 'Code',
        ])
            ->add('name', TextType::class, [
            'label' => 'Nom',
        ]);
    }

    $builder
        ->add('competence', EntityType::class, [
            'label' => 'Compétence',
            'choice_label' => 'name',
            'class' => Competence::class,
            'required' => false,
        ]);
    }

它有效,但是当我想编写功能测试时它不起作用。虽然我的单元测试正在工作。对于测试,我有一个数据库 AND database_test。为此,我将 .env.local 和 .env.test.local 与正确的 DATABASE_URL(主要和测试)一起使用。

public function testAdd()
{
    // Instance du client HTTP
    $client = static::createHttpBrowserClient();

    // Construction de la requête GET sur la page product
    $crawler = $client->request(
        'GET',
            getenv('APP_TEST_URL') . '/product/new'
        );
        
        $form = $crawler->selectButton('Ajouter')->form([
            'product[name]' => 'Product Test',
            'product[code]' => 'ABC_DEF',
            'product[competence]' => $this->entityManager->getRepository(\App\Entity\Competence::class)->findOneBy(['name' => 'BVB'])->getId(),

        ]);

        $client->submit($form);

        $crawler = $client->followRedirect();

        $this->assertSame(1, $crawler->filter('div.alert.alert-success')->count());
    }

我如何设置这个:

    /**
     * @var \Doctrine\ORM\EntityManager
     */
    private $entityManager;

    public function setUp(): void
    {
        $kernel = self::bootKernel();

        $this->entityManager = $kernel->getContainer()
            ->get('doctrine')
            ->getManager();
    }

    public function tearDown(): void
    {
        $client = static::createHttpBrowserClient();
        $client->restart();
    }

我的问题是关于 EntityType 能力。我必须输入我想要的 ID,但是对于数据库和 Database_URL 中的相同能力,ID 是不一样的。

所以我得到这个错误:

  1. App\Tests\E2e\Controller\ProductControllerTest::testAdd InvalidArgumentException:输入“product[competence]”不能将“3”作为值(可能的值:“”、“258”、“259”、“260”、“261” ”、“262”、“263”、“264”、“265”、“266”、“267”、“268”、“269”、“270”、“271”、“272”、“273”、 “274”、“275”、“276”、“277”、“278”、“279”)。

例如,即使我输入“258”,我也会出现此错误:“LogicException:请求未重定向。” 在 followRedirect() 上。

我不知道我是否走对了路,但我现在迷路了。我用教义.yaml 和 .env.* 尝试了很多东西

标签: formsphpunitentitysymfony4functional-testing

解决方案


推荐阅读