Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Hamcrest - Elegant way to test complex object with samepropertyvaluesas

I have quite complex object structure (with bunch of primitive fields and object references) and want to test all fields except -a few- of them. As an example;

ComplexObject actual = generateMagically("someInput");
ComplexObject expected = ActualFunction.instance.workMagically(actual);

// we want to be sure that workMagically() would create a new ComplexObject
// with some fields are different than "actual" object.

// assertThat(actual, samePropertyValuesAs(expected)); would check all fields.
// what I want is actually; - notice that "fieldName1" and "fieldName2" are 
// primitives belong to ComplexObject
assertThat(actual, samePropertyValuesExceptAs(expected, "fieldName1", "fieldName2"))

Since I don't want to check all fields manually, I believe there must be a way to write that test elegantly. Any ideas?

Cheers.

like image 410
tugcem Avatar asked Feb 26 '16 10:02

tugcem


1 Answers

You should have a look at shazamcrest, a great Hamcrest extension that offers what you need.

assertThat(expected, sameBeanAs(expectedPerson).ignoring("fieldName1").ignoring("fieldName2"));

See https://github.com/shazam/shazamcrest#ignoring-fields

like image 105
Ruben Avatar answered Sep 20 '22 22:09

Ruben