當您通過瀏覽器使用該應用程式時,您發送了一個錯誤的值,系統會檢查表單中的錯誤,如果出現問題(在這種情況下確實如此),它會重定向并在被指控者下方寫入默認錯誤訊息場地。
這是我試圖用我的測驗用例斷言的行為,但我遇到了一個我沒想到的 \InvalidArgumentException。
我將 symfony/phpunit-bridge 與 phpunit/phpunit v8.5.23 和 symfony/dom-crawler v5.3.7 一起使用。這是它的外觀示例:
public function testPayloadNotRespectingFieldLimits(): void
{
$client = static::createClient();
/** @var SomeRepository $repo */
$repo = self::getContainer()->get(SomeRepository::class);
$countEntries = $repo->count([]);
$crawler = $client->request(
'GET',
'/route/to/form/add'
);
$this->assertResponseIsSuccessful(); // Goes ok.
$form = $crawler->filter('[type=submit']->form(); // It does retrieve my form node.
// This is where it's not working.
$form->setValues([
'some[name]' => 'Someokvalue',
'some[color]' => 'SomeNOTOKValue', // It is a ChoiceType with limited values, where 'SomeNOTOKValue' does not belong. This is the line that throws an \InvalidArgumentException.
)];
// What I'd like to assert after this
$client->submit($form);
$this->assertResponseRedirects();
$this->assertEquals($countEntries, $repo->count([]));
}
這是我收到的例外訊息:
InvalidArgumentException: Input "some[color]" cannot take "SomeNOTOKValue" as a value (possible values: "red", "pink", "purple", "white").
vendor/symfony/dom-crawler/Field/ChoiceFormField.php:140
vendor/symfony/dom-crawler/FormFieldRegistry.php:113
vendor/symfony/dom-crawler/Form.php:75
此處測驗的 ColorChoiceType 非常標準:
public function configureOptions(OptionsResolver $resolver): void
{
$resolver->setDefaults([
'choices' => ColorEnumType::getChoices(),
'multiple' => false,
)];
}
我能做的是包裝在一個 try-catch 塊中,它設定錯誤值的行。它確實會提交表單并繼續下一個斷言。這里的問題是表單被認為已提交且有效,它為顏色欄位(列舉集的第一選擇)強制了一個適當的值。當我在瀏覽器中嘗試這個時,這不是我得到的(參見介紹)。
// ...
/** @var SomeRepository $repo */
$repo = self::getContainer()->get(SomeRepository::class);
$countEntries = $repo->count([]); // Gives 0.
// ...
try {
$form->setValues([
'some[name]' => 'Someokvalue',
'some[color]' => 'SomeNOTOKValue',
]);
} catch (\InvalidArgumentException $e) {}
$client->submit($form); // Now it submits the form.
$this->assertResponseRedirects(); // Ok.
$this->assertEquals($countEntries, $repo->count([])); // Failed asserting that 1 matches expected 0. !!
如何在我的測驗用例中模擬瀏覽器行為并對其進行斷言?
uj5u.com熱心網友回復:
您似乎可以在 DomCrawler\Form 組件上禁用驗證。基于官方檔案here。
這樣做,現在可以按預期作業:
$form = $crawler->filter('[type=submit']->form()->disableValidation();
$form->setValues([
'some[name]' => 'Someokvalue',
'some[color]' => 'SomeNOTOKValue',
];
$client->submit($form);
$this->assertEquals($entriesBefore, $repo->count([]); // Now passes.
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/453311.html
上一篇:從控制器訪問JWT資料的有效方法
下一篇:如何用黑色更改接觸中的像素顏色集
