Hamcrest - An elegant way to test a complex object with the same properties

I have a rather complicated object structure (with a bunch of primitive fields and object references) and you want to test all the 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 do not want to check all the fields manually, I believe that there should be a way to write this test elegantly. Any ideas?

Greetings.

+5
source share
3 answers

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

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

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

+7
source

In general, I see two solutions if ComplexObject can be changed independently.

You can enter an interface representing ComplexObject properties that change to ActualFunction . Then you can check if all the properties of this new interface have changed. This will require ComplexObject implement this new interface.

Another approach would be to replace the ComplextObject properties that were modified by ActualFunction with a new property of a new type that contains all these properties. A better option would be to let ActualFunction return an instance of the new type.

0
source

The last time I had similar requirements, I came to the conclusion that manually creating code and tests to confirm that some values ​​are being updated is inherently unstable and error prone.

I screened the fields in the bag object and generated the Java source files for both the package class itself and the copier at compile time. Thus, you can test the actual code (generator) and have the actual domain definition in one place, so the copy code cannot be outdated.

The property description language can be anything you prefer, from a JSON schema to XML to Java itself (Java example - user annotations should be used from a generator)

 public class MyBag { @Prop public int oh; @Prop public String yeah; } 
0
source

Source: https://habr.com/ru/post/1243933/


All Articles