我想在一些 API 中發出請求,所以我做了這個:
pub fn address_by_alias(node_url: &str, alias: &str) -> Result<(), Box<dyn std::error::Error>> {
let full_url = format!("{}/addresses/alias/by-alias/{}", node_url, alias);
let response = reqwest::blocking::get(full_url)?.json()?;
dbg!(response);
Ok(())
}
我想寫一個測驗,終端回傳這個錯誤
#[test]
fn test_address_by_alias() {
let response = address_by_alias("https://lunesnode.lunes.io", "gabriel");
let response_json = "address: 3868pVhDQAs2v5MGxNN75CaHzyx1YV8TivM";
assert_eq!(response_json, response)
}
錯誤:
assert_eq!(response_json, response)
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ no implementation for `&str == Result<(), Box<dyn std::error::Error
我該如何解決這個問題?
uj5u.com熱心網友回復:
現在您的address_by_alias函式正在回傳單位型別 (),因此無法將 () 與 a&str和 receive進行比較true。您需要修改address_by_alias.
您可以將從請求中收到的回應 JSON 作為 HashMap<String, String> 回傳:
pub fn address_by_alias(
node_url: &str,
alias: &str,
) -> Result<HashMap<String, String>, Box<dyn std::error::Error>> {
let full_url = format!("{}/addresses/alias/by-alias/{}", node_url, alias);
Ok(reqwest::blocking::get(full_url)?.json::<HashMap<String, String>>()?)
}
因此,當您執行時,address_by_alias您將能夠將來自請求的回應值存盤在測驗范圍內。
對于測驗部分,您可以手動創建一個HashMap<String, String>可以與address_by_alias回傳的內容進行比較的內容:
#[test]
fn test_address_by_alias() {
let response = address_by_alias("https://lunesnode.lunes.io", "gabriel").unwrap();
let mut response_json = HashMap::new();
response_json.insert(
"address".to_string(),
"3868pVhDQAs2v5MGxNN75CaHzyx1YV8TivM".to_string(),
);
assert_eq!(response_json, response);
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/422902.html
標籤:
