mmnaseri / spring-data-mock

Mock facility for Spring Data repositories
MIT License
135 stars 44 forks source link

Bug if the @Id field is private but has a public getter #192

Open pfichtner opened 1 year ago

pfichtner commented 1 year ago

When having a private @Id annotated field that has an public getter spring-data-mock fails with

com.mmnaseri.utils.spring.data.error.DataOperationExecutionException: Method call resulted in internal error: public java.lang.Object com.mmnaseri.utils.spring.data.repository.CrudRepositorySupport.save(java.lang.Object)
        at com.mmnaseri.utils.spring.data.domain.impl.MethodInvocationDataStoreOperation.execute(MethodInvocationDataStoreOperation.java:43)
        at com.mmnaseri.utils.spring.data.proxy.impl.DataOperationInvocationHandler.invoke(DataOperationInvocationHandler.java:92)
        at com.sun.proxy.$Proxy4.save(Unknown Source)
        at com.mmnaseri.utils.spring.data.dsl.factory.RepositoryFactoryBuilderTest.privateIdFieldIssue(RepositoryFactoryBuilderTest.java:485)
Caused by: java.lang.IllegalStateException: Failed to set property value through the field private java.lang.Long com.mmnaseri.utils.spring.data.dsl.factory.RepositoryFactoryBuilderTest$EntityWithAnnotatedIdFieldAndGetter.id
        at com.mmnaseri.utils.spring.data.tools.PropertyUtils.setPropertyValue(PropertyUtils.java:162)
        at com.mmnaseri.utils.spring.data.repository.CrudRepositorySupport.save(CrudRepositorySupport.java:51)
        at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
        at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
        at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
        at java.lang.reflect.Method.invoke(Method.java:498)
        at com.mmnaseri.utils.spring.data.domain.impl.MethodInvocationDataStoreOperation.execute(MethodInvocationDataStoreOperation.java:38)
        ... 40 more

This is because https://github.com/mmnaseri/spring-data-mock/blob/e8547729050c9454872a1038c23bb9b1288c8654/spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/tools/PropertyUtils.java#L155 only checks if the field is not final when changing it to be accessible. The code also should check if the field is private.

Testcase showing the problem added, please move the code as desired.