如何为 reqwest 编写测试?

How to write a test for reqwest?

我想在一些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(())
}

我想写个测试,终端return这个错误

#[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

我该如何解决这个问题?

现在您的 address_by_alias 函数正在 returning unit-type (),因此无法将 () 与 &str 进行比较并接收 true.您需要修改 address_by_alias 的 return 值。

您可以 return 从请求中收到的响应 JSON 作为 HashMap:

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 returns:

进行比较
#[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);
}