You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Lumen 5.6中seeJson()方法断言失败问题排查求助

Fixing the LinkCreationTest::fails_if_no_url_given Test Failure

Hey there, let's get this test sorted out quickly! The root of your problem is a mismatch between the JSON structure your test is expecting and what Laravel's validation actually returns.

What's Going Wrong

Your test is trying to assert that it finds the JSON snippet ["url":"Please enter a URL to shorten."] — but there are two key issues here:

  1. That syntax is invalid (arrays don't use key-value pairs like that; you likely intended an object structure instead)
  2. More critically, Laravel returns validation errors as an array per field, even for a single error. So the actual response your API sends back looks like this:
    {"url": ["Please enter a URL to shorten."]}
    

Your controller code is totally correct — the custom error message is set properly. The problem lives entirely in your test's assertion logic.

How to Fix It

Update your test to match the actual JSON structure Laravel sends back. Here are a few straightforward ways to do this:

Option 1: Use assertJson with the correct structure

If you're using Laravel's built-in test helpers, adjust your assertion to expect an array for the url field:

public function fails_if_no_url_given()
{
    // Send a POST request without the required url parameter
    $response = $this->post(route('links.store'), []);

    // Assert the exact JSON structure matches what Laravel returns
    $response->assertJson([
        'url' => ['Please enter a URL to shorten.']
    ]);
}

Option 2: Use assertJsonFragment for flexible matching

If you just need to confirm the error message exists (without strict checks on the full structure), use assertJsonFragment with the valid array format:

$response->assertJsonFragment([
    'url' => ['Please enter a URL to shorten.']
]);

Option 3: Check for the error message directly in the array

For even more flexibility, you can verify the specific message is present in the url error array:

$response->assertJson(fn ($json) => in_array('Please enter a URL to shorten.', $json['url']));

Why Laravel Returns Errors This Way

Laravel's validation system is built to handle multiple error messages per field (e.g., if a field fails both required and url rules, you'd get two messages in the array). Even when there's only one error, it wraps it in an array to keep the response structure consistent across all validation failures.

内容的提问来源于stack exchange,提问作者Jio M.

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.21 04:12:52