mockito / mockito-kotlin

Using Mockito with Kotlin
MIT License
3.09k stars 198 forks source link

InjectMocks doesn't work when declaring a default constructor with default values #439

Open juan-palacios opened 2 years ago

juan-palacios commented 2 years ago

I've asked the question here and there's a code example: https://stackoverflow.com/questions/68933185/injectmocks-doesnt-work-with-kotlin-constructor-arguments-with-default-values

I think when Mockito tries to inspect the constructor to match it to declared mocks, it finds more parameters than we put in the code when writing the constructor (e.g., a 3 parameter constructor actually has 5 parameters when it gets inspected).

juan-palacios commented 2 years ago

It looks like the issue is explained by this: https://stackoverflow.com/questions/53912047/two-additional-types-in-default-constructor-in-kotlin

Perhaps mockito-kotlin should filter out synthetic constructors? 🤔

Although a more robust strategy might be to properly handle the bit mask 🤔

juan-palacios commented 2 years ago

Could mockito-kotlin provide a custom MemberAccessor that wraps ReflectionMemberAccessor to check if one of the parameters is the DefaultConstructorMarker? If it isn't, it can delegate to the ReflectionMemberAccessor and same same.

However if it finds the DefaultConstructorMarker parameter, it can figure out what the bit mask should be, add it along with a null value for the marker to the list of arguments and then instantiate the class.

holubec-petr commented 4 months ago

Any progress with this issue?

I'm having the same troubles with Mockito 5.11.0 and Mockito-Kotlin 5.2.1 now.

The InjectMocks annotation does not correctly work regardless of whether a mock for the property with a default value is present in the test or not.