Avatar of the person chatting

Write test case code for the send_request function of the following code use crate::rest::Rest; mod rest; #[derive(serde::Serialize, serde::Deserialize)] struct Response { data: String, status: u16, } #[tauri::command] async fn send_request(method: &str, url: &str, body: Option<&str>) -> Result { let rest = Rest::new(); let response = rest.rest_call(method, url, body).await; Ok(Response { data: response.data.to_string(), status: response.status, }) }

Here's an example of test case code for the send_request function:

rustCopy code
#[cfg(test)] mod tests { use super::*; use mockito::{mock, Matcher}; #[tokio::test] async fn test_send_request() { // Arrange let expected_response = Response { data: "test data".to_string(), status: 200, }; let method = "GET"; let url = "http://example.com/test"; let body = Some("test body"); let mock_server = mock(method, Matcher::Regex(url)) .with_body(serde_json::to_string(&expected_response).unwrap()) .with_status(200) .create(); // Act let response = send_request(method, &mockito::server_url(), body).await.unwrap(); // Assert assert_eq!(response.data, expected_response.data); assert_eq!(response.status, expected_response.status); mock_server.assert(); } }

In this test case, we're using the mockito crate to set up a mock HTTP server that will respond to requests with the expected response JSON for the given URL and HTTP method. We then call send_request with the method, URL, and body, and assert that the response data and status match the expected values. Finally, we assert that the mock server was hit with the expected request.