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

Time:09-02

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.

CodePudding user response:

Are you not invoking the methods in incorrect sequence here? assertThat(results).isEqualTo(expectedMatch).usingRecursiveComparison().ignoringFields("id");

You probably need to invoke comparison and ignore the fields before equals.

assertThat(results).usingRecursiveComparison().ignoringFields("id").isEqualTo(expectedMatch);

CodePudding user response:

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));
  }
  • Related