Search code examples
javaunit-testingjunitassertj

Ignoring a field in Map<String, Object> that is a member of a class while testing


I have an Object called ReconciliationResult

public class ReconciliationResult {

  Map<String, Object> recordValue;
  List<Object> keyValues;
  Origin origin;
  ReconciliationResultStatus status;

  public enum ReconciliationResultStatus {
    INVALID_KEY,
    DUPLICATE_KEY,
    MATCHING,
    NON_MATCHING;
  }

  public enum Origin {
    LEFT_SIDE,
    RIGHT_SIDE;
  }
}

I am comparing an instance of this object to the result of my classUnder test

EDIT:

    List<ReconciliationResult> results =
        reconciliationRegistry.getRecon("BPSVsGPM_TradeDated").reconcile(TESTDATE);
    assertThat(results).usingRecursiveComparison().ignoringFields("id").isEqualTo(expectedMatch);

However I don't want to test the ID field in the recordValue field inside of my ReconciliationResult Object. I don't want to test it because I have multiple tests in this class and every time I insert something to my embedded PG db the ID increments so on assertions, ID is never the same.

I have tried clearing the database after every run using JdbcTemplate, but that didn't work I also added the @DirtiesContext annotation since the tests are transactional. Alas those approaches didn't work as well.

Any clarification on the matter would be greatly appreciated. Please let me know if you need any more information from me.


Solution

  • I had to do the comparison of the map separately since the ignoringFields is for object members, and can't go into the map specifically to ignore the key. I created a helper function to filter out the ID field in my Map<String, Object> field during comparison.

        assertThat(results)
            .usingRecursiveComparison()
            .ignoringFields("recordValue", "keyValues")
            .isEqualTo(expectedBreak);
        assertThat(filterIgnoredKeys(results.get(0).getRecordValue()))
            .usingRecursiveComparison()
            .isEqualTo(filterIgnoredKeys(expectedBreak.get(0).getRecordValue()));
    
    
      private static <V> Map<String, V> filterIgnoredKeys(Map<String, V> map) {
        return Maps.filterKeys(map, key -> !IGNORED_FIELDS.contains(key));
      }