【发布时间】:2018-01-03 17:24:54
【问题描述】:
以下示例来自official documentation:
use AppBundle\Form\Type\TestedType;
use AppBundle\Model\TestObject;
use Symfony\Component\Form\Test\TypeTestCase;
class TestedTypeTest extends TypeTestCase
{
public function testSubmitValidData()
{
$formData = array(
'test' => 'test',
'test2' => 'test2',
);
$form = $this->factory->create(TestedType::class);
$object = TestObject::fromArray($formData);
// submit the data to the form directly
$form->submit($formData);
$this->assertTrue($form->isSynchronized());
$this->assertEquals($object, $form->getData());
$view = $form->createView();
$children = $view->children;
foreach (array_keys($formData) as $key) {
$this->assertArrayHasKey($key, $children);
}
}
}
但是,使用真正的单元测试方法,测试应该只包含一个单独的类作为SUT,其他所有内容都应该是Test Doubles,如存根、模拟对象...
我们应该如何使用像模拟对象这样的测试替身对 Symfony 表单进行单元测试?
我们可以假设一个简单的表单类:
class TestedType extends AbstractType
{
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add('firstname', TextType::class, [
'label' => 'First name',
'attr' => [
'placeholder' => 'John Doe',
],
])
}
}
【问题讨论】:
标签: php symfony unit-testing mocking phpunit