Symfony 为什么$form->;isValid()在测试时返回false,尽管它';这在生产中是真的吗?
我正在使用Symfony 3.4,并且正在为我的操作编写测试 正如标题Symfony 为什么$form->;isValid()在测试时返回false,尽管它';这在生产中是真的吗?,symfony,testing,symfony-3.4,Symfony,Testing,Symfony 3.4,我正在使用Symfony 3.4,并且正在为我的操作编写测试 正如标题$form->isValid()中提到的,它返回false,尽管在生产环境中测试表单时效果良好 在我的测试中,我尝试模拟POST请求,如下所示: $crawler = $this->_client->request('GET', $this->_router->generate('product_new')); $form = $crawler->filter('form')->form()
$form->isValid()
中提到的,它返回false
,尽管在生产环境中测试表单时效果良好
在我的测试中,我尝试模拟POST请求,如下所示:
$crawler = $this->_client->request('GET', $this->_router->generate('product_new'));
$form = $crawler->filter('form')->form();
$values = $form->getPhpValues();
$values['product']['code'] = 'PRD';
$values['product']['name'] = 'TEST PRODUCT';
$values['product']['price'] = 550;
$this->_client->request($form->getMethod(), $form->getUri(), $values, $form->getPhpFiles());
$response = $this->_client->getResponse();
// the response should return 302 because I'm doing redirection after submitting the form
// so this one should return true
$this->assertEquals(Response::HTTP_FOUND, $response->getStatusCode());
这是ProductController
类中的操作:/**
* @Route("/new", name="product_new")
* @Method({"GET", "POST"})
*/
public function createAction(){
$product = new Product();
$form = $this->createForm(ProductType::class, $product);
$form->handleRequest($request);
// when I remove $form->isValid() the test works fine
if ($form->isSubmitted() && $form->isValid()) {
$em = $this->getDoctrine()->getManager();
$em->persist($product);
$em->flush();
return $this->redirectToRoute('product_show', array('code' => $product->getCode()));
}
return $this->render('@Commerce/product/new.html.twig', array(
'product' => $product,
'form' => $form->createView()
));
}
我在这里遗漏了什么?可能是提交由
getPhpValues()返回的空字段有问题。
?您是否尝试过使用爬虫获取按钮,然后使用$client->submit($form)代码>如“文档”部分所述?请参阅:@dbrumann此方法的问题是,我获得colleciton字段的“不可访问字段”异常!啊,如果你真的在表单集合中使用它,那么拥有它是有意义的。您是否在test.log中看到任何错误?我还建议为测试环境启用探查器(如果尚未启用),然后从测试中的响应标头中提取探查器url,以便更仔细地查看表单验证,了解其无效的原因。@dbrumann我找到了如何启用探查器并获取其url,谢谢你的提示,我会检查为什么没有验证working@dbrumann天哪,我简直不敢相信,我发现问题出在我设置的字段名上,而不是地址!!现在它开始工作了,再次感谢分析器提示:)