Home > Software engineering >  How to write a test for reqwest?
How to write a test for reqwest?

Time:01-26

I want to make a request in some API, so I made this:

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(())
}

I want to write a test, the terminal return this error

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

Error:

         assert_eq!(response_json, response)
   |     ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ no implementation for `&str == Result<(), Box<dyn std::error::Error

How can I resolve this?

CodePudding user response:

Right now your address_by_alias function is returning the unit-type (), so there's no way to compare () with a &str and receive true. You'll need to modify the return value of address_by_alias.

You can return the response JSON received from the request as a 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>>()?)
}

So this way when you execute address_by_alias you'll be able to store the response value from the request within the test scope.

And for the test part you can manually create a HashMap<String, String> that can be compared with what 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);
}
  •  Tags:  
  • Related