1

I have a method that is migrating old JSON structure to a new one that I would like to test, but there is one randomly generated property (UUID) that I would like to ignore.

The interesting part of the object looks like this:

val expected = FooterContainer(id = UUID.fromString("11914145-9775-4675-9c65-54bbd369fb2c"), title = null, flowType=ContainerType.ROWS, elements=listOf() //the rest is not important.

The JSON to be converted looks totally different from this object, but this is the purpose of the method - to convert it to a new model.

val json = """[{"type": "list", "items": [{"link": "www.something.com", "type": "link", "label": "Some label"},
            {"type": "text", "label": "Another label"}, {"type": "text", "label": "Other label"},
            {"type": "text", "label": "yet another label"}, {"type": "text", "label": "[email protected]"}]

et cetera.

The below code worked as expected:

val gson: JsonElement = Gson().fromJson(json, JsonElement::class.java)

    // when
    val converted = with(ClientDataRepository()) {
        gson.readFooter()
    }

until I had to introduce a new field in FooterContainer object, which was val id: UUID

The method readFooter() is generating the UUID randomly, which is an expected behaviour.

But now, I cannot just assign a random (or hardcoded, as in the example code above) UUID to the expected class, which is logical - two randomly generated UUIDs will never be the same.

when I run the test, I obviously get:

Expected :FooterContainer(id=11914145-9775-4675-9c65-54bbd369fb2c,
Actual   :FooterContainer(id=7ba39ad0-1412-4fda-a827-0241916f8558,

Now, is there a possibility to ignore the id field for this test? It is not important from the test perspective, but the rest is.

3 Answers 3

2

Try JsonUnit. In this case you can modify your code in next way:

assertThatJson("{\"id\":${json-unit.ignore}}").isEqualTo("{\"id\": 11914145-9775-4675-9c65-54bbd369fb2c}");
Sign up to request clarification or add additional context in comments.

Comments

1

You can simply copy the id field from the actual object to the expected:

val converted = with(ClientDataRepository()) {
    gson.readFooter()
}

val expected = FooterContainer(id = converted.id, title = null, flowType=ContainerType.ROWS, elements=listOf()) //the rest is not important.
Assertions.assertThat(converted).isEqualTo(expected);

If you are using assertJ, there is a stright forward solution:

Assertions.assertThat(converted).isEqualToIgnoringGivenFields(expected, "id")

Comments

0

You can use something like json-assert (https://github.com/skyscreamer/JSONassert) that support ignoring keys - https://stackoverflow.com/a/44328139/4473822

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.