Ask Your Question
3

How can you assert_eq JSON in Rust tests when its keys keep getting reordered?

asked 2022-01-31 11:00:00 +0000

huitzilopochtli gravatar image

edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted
1

answered 2022-05-17 12:00:00 +0000

devzero gravatar image

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.

edit flag offensive delete link more

Your Answer

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

Add Answer


Question Tools

Stats

Asked: 2022-01-31 11:00:00 +0000

Seen: 7 times

Last updated: May 17 '22