1 use anyhow::{Context, Result}; 2 request(url: &str) -> Result<reqwest::blocking::Response>3pub fn request(url: &str) -> Result<reqwest::blocking::Response> { 4 reqwest::blocking::get(url).context("Failed to make request") 5 } 6 7 #[cfg(test)] 8 mod test { 9 use super::*; 10 11 use httpmock::prelude::*; 12 13 #[test] test_request()14 fn test_request() { 15 // Start a lightweight mock server. 16 let server = MockServer::start(); 17 18 // Create a mock on the server. 19 let hello_mock = server.mock(|when, then| { 20 when.method(GET) 21 .path("/translate") 22 .query_param("word", "hello"); 23 then.status(200) 24 .header("content-type", "text/html; charset=UTF-8") 25 .body("Hallo"); 26 }); 27 28 // Send an HTTP request to the mock server. This simulates your code. 29 let response = request(&server.url("/translate?word=hello")).unwrap(); 30 31 // Ensure the specified mock was called exactly one time (or fail with a detailed error description). 32 hello_mock.assert(); 33 34 // Ensure the mock server did respond as specified. 35 assert_eq!(response.status(), 200); 36 37 // Ensure the body contains the results we expect 38 assert_eq!(response.text().unwrap(), "Hallo") 39 } 40 } 41