Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

In Rust tests, how to assert_eq some json that keeps reordering its keys

My Rust lib does some operations on JSON, and in unit tests I need to ensure the correctness of the lib. Yet, json to string conversion keeps key order unstable. I do NOT want to modify the lib to include json sorting, but I do need to compare the results effectively in my unit tests. What can I do to simplify this comparison?

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

The simplest answer would be to parse both strings and compare the parsed values for equality. This compares the strings semantically instead of literally, which is what you want anyway. Aside from key order, other non-semantic differences in the strings (like amounts of insignificant whitespace or escaped vs unescaped characters) will also be ignored.

assert_eq!(
    a.parse::<serde_json::Value>().unwrap(),
    b.parse::<serde_json::Value>().unwrap()
);

If your library itself doesn’t depend on serde_json, you can include it as a dev dependency to have it available during tests without requiring users of your library to depend on it transitively.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading