在 PHPUnit 的联系表单中设置 AbstractType 的名称

setting the name of an AbstractType in a contact form for PHPUnit

我正在尝试使用 PHPUnit 测试联系表单的方法

public function testContact()
{
    $client = static::createClient();

    $form = $crawler->selectButton('Submit')->form();

    $form['blogbundle_enquirytype[name]']       = 'name';
    // other form field assignments here

    $crawler = $client->submit($form);

    $this->assertEquals(1, $crawler->filter('.blogger-notice:contains("Your contact enquiry was successfully sent. Thank you!")')->count());
}

PHPUnit 无法识别 blogbundle_enquirytype(无法访问的字段),大概是因为控制器像这样实例化它

$enquiry = new Enquiry();
$form = $this->createForm(EnquiryType::class, $enquiry);

所以尽管 AbstractType:

class EnquiryType extends AbstractType
{

public function buildForm(FormBuilderInterface $builder, array $options)
{
    $builder->add('name');
    $builder->add('email', EmailType::class);
    $builder->add('subject');
    $builder->add('body', TextareaType::class);
}

public function getName(){
    return 'blogbundle_enquirytype';
}

是否有另一种方法来设置 EnquiryType 的名称,或者让 Phpunit 识别表单的方法?

这是表格

<form action="/contact" method="post"  class="blogger">

    <div><label for="enquiry_name" class="required">Name</label><input type="text" id="enquiry_name" name="enquiry[name]" required="required" maxlength="255" /></div>
    <div><label for="enquiry_email" class="required">Email</label><input type="email" id="enquiry_email" name="enquiry[email]" required="required" /></div>
    <div><label for="enquiry_subject" class="required">Subject</label><input type="text" id="enquiry_subject" name="enquiry[subject]" required="required" maxlength="50" /></div>
    <div><label for="enquiry_body" class="required">Body</label><textarea id="enquiry_body" name="enquiry[body]" required="required"></textarea></div>

    <input type="hidden" id="enquiry__token" name="enquiry[_token]" value="-eZq7Go6ELXykluf0Fca_CPvzeB3yEUj2yuOnyamYBU" />

    <input type="submit" value="Submit" />
</form>

试试这个:

$form['enquiry[name]']       = 'name';

而不是:

$form['blogbundle_enquirytype[name]']       = 'name';

更新:

关于 migration guide 到 symfony3:

The getBlockPrefix() method was added to the FormTypeInterface in replacement of the getName() method which has been removed.

因此,如果您从以下更改表单方法,则可以继续使用您的测试代码 class:

    /**
     * Returns the prefix of the template block name for this type.
     *
     * The block prefix defaults to the underscored short class name with
     * the "Type" suffix removed (e.g. "UserProfileType" => "user_profile").
     *
     * @return string The prefix of the template block name
     */
    public function getBlockPrefix(){
    return 'blogbundle_enquirytype';
}

而不是这个:

public function getName(){
    return 'blogbundle_enquirytype';
}

希望对您有所帮助