2

I'm trying to do an AssertJ assertion filtering out the specific Map entries by their key. The only available method for ignoring - "ignoringFields" doesn't work since the map key is not a field (obviously).

Do you know if there are any way to do such a filtering? Probably custom comparator or anything else.

Here is the code sample for the problem: trying to ignore "Chapter 2" key value comparison.

Note: The real objects I have to compare are auto-generated complex and deep and can have many different maps with the same keys I need to ignore.

import lombok.Data;
import org.junit.jupiter.api.Test;

import java.util.HashMap;
import java.util.Map;

import static org.assertj.core.api.Assertions.assertThat;

public class TestAssertJ {

    @Test
    public void testBook() {
        HashMap<String, Chapter> b1Chapters = new HashMap<String, Chapter>() {{
            put("Chapter 1", new Chapter("text 1"));
            put("Chapter 2", new Chapter("text 2"));
        }};
        Book book = new Book("Harry Potter", b1Chapters);

        HashMap<String, Chapter> b2Chapters = new HashMap<String, Chapter>() {{
            put("Chapter 1", new Chapter("text 1"));
        }};
        Book book2 = new Book("Harry Potter", b2Chapters);

        assertThat(book)
                .usingRecursiveComparison()
                .ignoringFields("Chapter 2")
                .isEqualTo(book2);
    }

    @Data
    class Book {
        private final String title;
        private final Map<String, Chapter> chapters;
    }

    @Data
    class Chapter {
        private final String text;
    }
}
suamo
  • 21
  • 2
  • 1
    One hacky way of doing it would be using a custom comparator for the maps and computing the map difference to check if the only difference is the ignored keys that you have. You can use Guava Maps.difference method for it. Another alternative would be to remove all the ignored keys from maps before using the recursive comparison. – Çağatay Sel Mar 10 '23 at 22:44
  • Hi, I tried the approach related to remove the fields to be ignored from the map before the comparison, and it works. Thanks – Massimo Da Ros Aug 04 '23 at 15:37

0 Answers0