我正在尝试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>
答案 0 :(得分:1)
试试这个:
$form['enquiry[name]'] = 'name';
而不是:
$form['blogbundle_enquirytype[name]'] = 'name';
<强>更新强>
关于migration guide到symfony3:
getBlockPrefix()方法已添加到FormTypeInterface中 替换已删除的getName()方法。
因此,如果您更改表单方法,则可以继续使用测试类的代码:
/**
* 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';
}
希望这个帮助