https://kotlinlang.org logo
#mockk
Title
# mockk
m

Mattia Tommasone

02/11/2021, 10:22 PM
that’s a tricky one and there’s an open issue about it AFAIR. The thing is mockk still needs to somehow instantiate an instance of the class and thus execute a constructor. The bad answer to your question, then, is that ideally your constructors should not have side effects; a possible workaround could be to put them in a @PostConstruct method
p

Patrick Ramsey

02/11/2021, 10:25 PM
Out of curiosity: why does mockk need to create an instance and then substitute it? From what I can tell, mockk() doesn’t have the same behavior, and just returns a mock instance of the targeted class without its real constructor having ever been called.
is it a limitation of kotlin?
and thanks.
e

ephemient

02/11/2021, 10:27 PM
probably because
mockk()
is a function which is free to perform any proxy or objenesis magic it needs to achieve the result, but intercepting a constructor call is actually pretty difficult on the JVM, even more so than intercepting static calls
@Patrick Ramsey if you need this feature, try contributing it to mockk. it does not have enough developers.
p

Patrick Ramsey

02/11/2021, 10:28 PM
that’s good to know on both counts
and unfortunate. It’s a great tool.
I’ll keep that in mind.
thanks to you both
m

Mattia Tommasone

02/11/2021, 10:30 PM
+1 on both @ephemient’s comments, i could use a hand 🙂
p

Patrick Ramsey

02/11/2021, 10:30 PM
thank you for all your hard work!
m

Mattia Tommasone

02/11/2021, 10:30 PM
the most requested feature atm is also related to constructors, btw, it’s about being able to mock specific constructors with different behaviors depending on the parameters they take
p

Patrick Ramsey

02/11/2021, 10:32 PM
that, too, sounds both useful and like a giant pain to implement. 😆
and +1 on constructors not having side effects. Just trying to retrofit tests onto an existing codebase that’s in need of some improvement
thanks again all of you!
c

christophsturm

02/11/2021, 10:36 PM
I think mockito can mock without calling constructors. (I read that it uses objenesis to create classes without constuctor invocation)
p

Patrick Ramsey

02/11/2021, 10:36 PM
that was my memory as well, but it’s been a while
but I can massage things and accomplish what I want a different way I think.