vendredi 1 avril 2016

Test content of a collection attribute from a collection of objects

Sorry for this title that I try to make as clear as possible. Don't hesitate to edit to impove it.

My problem is that I would like to test the content of this structure and more specialy the content of B objects and assure that it correspond to specific A values :

public class A {
    String key;
    List<B> bs;
}

And my data have this form

List<A> as = [
    {
        key : "KEY1", 
        bs: [
            {val1:"val1", val2:"val2}
        ]
    },
    {
        key : "KEY2", 
        bs: [
            {val1:"val3", val2:"val4"}, 
            {val1:"val5", val2:"val6"}
        ]
    },
];

I would like to be able to test this structure without doing a pre treatment to get the List of B. By testing this structure I would like to be sure that there are two B for KEY2 and that first B has val3 and val4, the second val5 and val6.

At the moment, I have to create a map by key and test every entry. I would like to it in a more straightforward way if any exist.

Here is my actual test.

List<A> as = captor.getAllValues();
assertThat(as)
            .isNotNull()
            .hasSize(2)
            .extracting("key")
            .containsOnlyOnce(
                    tuple("KEY1"),
                    tuple("KEY2")
            );

    Map<String, A> estimationParPlateforme = indexBy(as, new Indexer<String, A>() {
        @Override
        public String apply(A a) {
            return a.getKey();
        }
    });

assertThat(as.get("KEY1").getBs())
            .isNotEmpty()
            .extracting(
                    "val1",
                    "val2"
            )
            .containsExactly(
                    tuple(
                            "val1",
                            "val2"
                    )
            );

assertThat(as.get("KEY2").getBs())
            .isNotEmpty()
            .extracting(
                    "val1",
                    "val2"
            )
            .containsExactly(
                    tuple(
                            "val3",
                            "val4"
                    ),
                    tuple(
                            "val5",
                            "val6"
                    )
            ); 

I think that it is a bit long for a test, and I would like to find a way to improve this. Do you have any solution?

Thanks for any help

Aucun commentaire:

Enregistrer un commentaire