One solution is to parse the JSON into a serdejson::Value and then use the asserteq! macro to compare the values recursively.
For example:
use serde_json::json;
#[test]
fn test_json() {
let expected = json!({
"name": "Alice",
"age": 30,
"address": {
"street": "123 Main St",
"city": "Seattle"
},
"phones": ["555-1234", "555-5678"]
});
let actual = json!({
"name": "Alice",
"age": 30,
"phones": ["555-5678", "555-1234"], // Keys reordered
"address": {
"city": "Seattle",
"street": "123 Main St" // Keys reordered
}
});
assert_eq!(expected, actual); // Fails because of key order
assert_eq!(
serde_json::to_value(expected).unwrap(),
serde_json::to_value(actual).unwrap()
); // Succeeds because keys are ignored
}
In this example, the expected and actual JSON objects have the same keys and values, but the order is different for some of the objects. Therefore, the first asserteq! macro would fail. However, by converting the objects into serdejson::Value and testing for equality, the keys are ignored and the test passes.
Please start posting anonymously - your entry will be published after you log in or create a new account. This space is reserved only for answers. If you would like to engage in a discussion, please instead post a comment under the question or an answer that you would like to discuss
Asked: 2022-01-31 11:00:00 +0000
Seen: 7 times
Last updated: May 17 '22
What are the Cordapp Certificates used for in terms of signing and interacting?
How can SSL be used with CqlSessionFactoryBean in Springboot Cassandra?
How to set up Database First configuration in Entity Framework 7 for MVC 6?
How can I address the issue of Content Security Policy blocking more than I had anticipated?
How do I resolve a 502 error when attempting to call an HTTPS REST API from an HTTP REST API?
What does borrowing or moving a value from `stdout` mean?