JavaHamcrest icon indicating copy to clipboard operation
JavaHamcrest copied to clipboard

HasProperty Matcher doesn't work with Java Records

Open rozagerardo opened this issue 2 years ago • 4 comments

Describe the bug I have the following simple assertion in my test:

hasProperty("name")

For the following record:

public record AnyDto(
    Long id,
    
    @NotBlank
    String name,
    
    String description) { }

And even though I can see the object does have the property (set with a value), the test fails.

I have tracked this down, and it seems the "issue" is generated in the PropertyUtil class, in the propertyDescriptorsFor method:

https://github.com/hamcrest/JavaHamcrest/blob/5d76642543b4d8c3e5f1b4cd4684d31be0724fde/hamcrest/src/main/java/org/hamcrest/beans/PropertyUtil.java#L49

This is what Introspector.getBeanInfo(fromObj.getClass(), stopClass) retrieves for a Record class:

Screen Shot 2022-10-26 at 15 17 30

If I change the AnyDto to a regular class, the test passes, because the Introspector method above does contain PropertyDescriptors for the class:

Screen Shot 2022-10-26 at 15 21 48

Note: the Record does contain name as a MethodDescriptor, maybe we can rely on these for the Records?

This is a related Stackoverflow Question: https://stackoverflow.com/questions/66982522/how-can-i-assert-hasproperty-with-a-java-record

rozagerardo avatar Oct 26 '22 18:10 rozagerardo

It would be nice if property descriptors would be supplemented with Class::getRecordComponents in the case that Class::isRecord is true

CC007 avatar Jan 24 '23 15:01 CC007