Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to compare two elements by using one of their attributes using Google Truth (Unit test)

I'm new to the Google Truth library and I was wondering if there was a way to compare two elements by using only one of their attributes. I know it is possible to do so with AssertJ so I was wondering if the same can be achieved with Truth.

I want to do something similar to this.

List list1 = Method1TocreateAList();
List list2 = Method2ToCreateAList();

//other code

//The test I want to achieve
assertThat(list2).compareElementsByUsing(x=>x.id = y)

like image 924
J. Lev Avatar asked Nov 19 '25 07:11

J. Lev


1 Answers

To compare lists based on a comparison other than plain equality, use comparingElementsUsing:

assertThat(list1).comparingElementsUsing(...).containsExactlyElementsIn(list2);

Add an inOrder() call to the end if you want to check order, too.

The only remaining trick is what to put in that ... section. For your case, since you want to compare on the value of a single field, you can use Correspondence.transforming:

assertThat(list1)
    .comparingElementsUsing(
        transforming(X::id, "has an ID of"))
    .containsExactlyElementsIn(list2);
like image 101
Chris Povirk Avatar answered Nov 21 '25 22:11

Chris Povirk



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!