[英]Symfony2 Custom form type using entity trying to test it
我正在嘗試測試我創建的表單類型,它使用帶有類實體的字段
這是表單的創建
$builder
->add('name', 'text')
->add('description', 'textarea')
->add('services', 'entity', array('class' => 'MyBundle:Service', 'group_by' => 'category.name', 'property' => 'name', 'multiple' => true, 'required' => false));
當我構建表單時,這非常好用,但后來我試圖對這種類型進行單元測試
按照此示例介紹如何測試自定義表單類型
我收到了這個錯誤
Symfony \\ Component \\ Form \\ Exception \\ Exception:無法加載類型“entity”
在此命令的單元測試開始時引發錯誤:
$type = new MyType();
$form = $this->factory->create($type);
有關如何修復此錯誤以便使用實體測試我的自定義表單類型的任何想法?
提前致謝
我想你不能用實體類型單元測試表單,因為它被定義為服務。 您是否嘗試過手動添加 ?
編輯:恕我直言你應該模擬實體類型,因為它涉及doctrine,這取決於現有的數據庫連接等等,加載完整的內核。 所以你不再進行單元測試了。 這將是一個功能測試。 也許這就是原因,為什么它在單元測試中不可用。
要正確創建表單,您需要在測試中使表單工廠可以使用該類型。 最簡單的方法是在使用PreloadedExtension類創建父窗體之前手動注冊它:
class TestedTypeTest extends TypeTestCase { protected function getExtensions() { $childType = new TestChildType(); return array(new PreloadedExtension(array( $childType->getName() => $childType, ), array())); } public function testSubmitValidData() { $type = new TestedType(); $form = $this->factory->create($type); // ... your test } }
在方法create中為第二個參數添加null。
$type = new MyType();
$form = $this->factory->create($type, null);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.