Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Use JSONAssert instead of Assert in JSONUtilTest to fix a flaky test
Flaky test case: cn.hippo4j.common.toolkit.JSONUtilTest.cn.hippo4j.common.toolkit.JSONUtilTest.assertToJSONString
hippo4j/infra/common/src/test/java/cn/hippo4j/common/toolkit/JSONUtilTest.java
Line 43 in 472d345
Problem
Test
assertToJSONString
inJSONUtilTest
is detected as flaky with the NonDex tool. The test failed with the following error:Root cause
In this test, two JSON strings are compared using Assert.assertEquals() in this part of the code:
hippo4j/infra/common/src/test/java/cn/hippo4j/common/toolkit/JSONUtilTest.java
Line 45 in 472d345
Using Assert.assertEquals() will lead to flaky tests due to mismatch in the order of properties or if there are nested structures. In this particular test case, JSON object(Foo) contains a nested object of the same type leading to difference in the order of properties thus making it a flaky test.
In this test, a hardcoded JSON string "EXPECTED_FOO_JSON" is compared with another JSON string created by JSONUtil.toJSONString(). The input to this method is an object of class Foo (test class present in JSONUtilTest).
Fix
Changed Assert.assertEquals() to JSONAssert.assertEquals() which is order insensitive.
How this has been tested?
Java: openjdk version "11.0.20.1"
Maven: Apache Maven 3.6.3
Command used -
Command used -
Command used -
NonDex test passed after the fix.
Alternate fix
Add
@JsonPropertyOrder({"id", "name", "foo"})
annotation to Foo class so that the order of properties whenever an object of this class is converted to JSON string remains same. Since the order now always remains same, the JSON string always matches with our expected string thus fixing the flaky test. This change will not impact code since Foo class is only used in tests.