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

Rocket.rs应用单元测试问题:POST请求返回404错误求助

Rocket.rs POST路由测试返回404的解决办法

你的POST测试返回404的核心原因是:路由中使用Form提取器接收表单数据,但测试请求没有设置正确的Content-Type请求头,导致Rocket无法匹配到对应的POST路由。

解决方案

方法1:手动添加Content-Type头

给POST请求添加application/x-www-form-urlencoded类型的请求头,让Rocket识别这是表单数据:

修改tests.rs中的add和delete测试:

#[test]
fn add() {
    let client = Client::tracked(rocket()).expect("valid rocket instance");
    let response = client.post(uri!(super::add))
        .header("Content-Type", "application/x-www-form-urlencoded")
        .body("note=This is a test")
        .dispatch();
    assert_eq!(response.status(), Status::Ok);
}

#[test]
fn delete() {
    let client = Client::tracked(rocket()).expect("valid rocket instance");
    let response = client.post(uri!(super::delete))
        .header("Content-Type", "application/x-www-form-urlencoded")
        .body("noteid=1")
        .dispatch();
    assert_eq!(response.status(), Status::Ok);
}

方法2:使用Rocket内置的form()方法

Rocket的测试客户端提供了form()方法,可以自动处理表单数据和对应的请求头,写法更简洁:

#[test]
fn add() {
    let client = Client::tracked(rocket()).expect("valid rocket instance");
    let response = client.post(uri!(super::add))
        .form(&super::NoteForm { note: "This is a test".into() })
        .dispatch();
    assert_eq!(response.status(), Status::Ok);
}

#[test]
fn delete() {
    let client = Client::tracked(rocket()).expect("valid rocket instance");
    let response = client.post(uri!(super::delete))
        .form(&super::NoteID { noteid: 1 })
        .dispatch();
    assert_eq!(response.status(), Status::Ok);
}

原理说明

Rocket的Form提取器默认只会解析Content-Type为application/x-www-form-urlencoded的请求。你的测试中只传了body内容但没设置该头,Rocket会判定这个请求不匹配对应的POST路由,因此返回404状态码。而GET请求没有这类要求,所以index测试可以正常通过。

内容的提问来源于stack exchange,提问作者Oscar S

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.01 21:30:53