`@InjectMockKs` can't be used with constructor injection
See original GitHub issueHi. Not sure whether to report this as a bug or as a feature request.
I did some searching to see if this issue has already been discussed or raised somewhere, but I couldn’t find anything.
Take the following example test class:
@ExtendWith(MockKExtension::class)
internal class SubjectTest(
@MockK private val xServiceMock: XService,
@MockK private val yServiceMock: YService,
) {
@InjectMockKs
private lateinit var subject: Subject
// Test functions here.
}
To avoid having to use the Keyword of Shame, I prefer to use constructor injection for the Class Under Test (Subject
) as well, so I try to rewrite it as follows:
@ExtendWith(MockKExtension::class)
internal class SubjectTest(
@MockK private val xServiceMock: XService,
@MockK private val yServiceMock: YService,
@InjectMockKs private val subject: Subject,
) {
// Test functions here.
}
I would expect this to work the same, but unfortunately this results in the following error:
No ParameterResolver registered for parameter [subject] in constructor...
I’ve tried this with MockK versions 1.12.0
and 1.12.1
, and it fails the same way in both.
It would be nice if @InjectMockKs
would work through constuctor injection as well. In my opinion, lateinit var
is ugly, and I prefer not to use it unless absolutely necessary.
Is there a specific reason why this doesn’t work, like with the @MockK
annotations? Or is this a bug?
Thanks.
Issue Analytics
- State:
- Created 2 years ago
- Reactions:1
- Comments:11
Top GitHub Comments
This is indeed an unsupported behavior; MockKExtension does not take into account parameters annotated with
@InjectMocks
.It should be possible, though, to handle them in the
resolveParameters
method and inject the mocks; not sure if parameter order is going to be relevant here (it likely is), so we may need to force the@InjectMocks
parameter to be the last one, but it shouldn’t be a big deal.Yes please, that would be amazing! 🙏