Hi, I’m desperately trying to mock a superclass me...
# mockk
m
Hi, I’m desperately trying to mock a superclass method but I can’t seem to find a way… 😢 I even tried to use
mockkConstructor()
on the superclass and then stub with
anyConstructed()
, but it didn’t work. Is this even possible to achieve with Mockk? The docs don’t say anything about this scenario.
m
uhm is the method externally visible from the class you are mocking?
m
yes, it’s a public method of the superclass, declared as
open suspend fun
. It’s overridden in the subclass and calls the super before doing other stuff. For this test I need to stub it, but can’t find a way.
m
uhm are you saying you want to stub just the
super()
call and have the subclass function invoke the real function?ù
that smells a bit to me 😄
m
Yeah I know, sadly it’s not my class, it was written like that, cannot refactor it at the moment. 😕 I have to deal with it as it is right now. Re-reading the docs now I noticed something: does anyConstructed() matches any available constructor? The docs say that if you have several you can use constructedWith(), but actually these classes have only 1 ctor (with 12 params, I know don’t tell me… 🤦‍♂️ ). So when I use anyConstructed<Superclass>() will it match? Currently it seems not because the super method is still executing
m
that is a good question i don’t have an answer for off the top of my head 😄 i.e., IDK if
anyConstructed
will match constructors being called when instantiating a superclass with
super
I’m guessing it will, but it’s an educated guess
this being said, why don’t you stub the subclass method altogether?
m
can’t stub it because it’s the object under test 😂 Anyway, I’ve come to the conclusion that it’s really a hassle and we can’t find a solution right now. The only workaround a teammate found was to encapsulate che super call into a private method that can be stubbed like
Copy code
coEvery { underTest["execute"](request) }
so that’s the route I’ll have to go down; in the near future we will get rid of inheritance using a decorator and this problem will disappear. Big thanks anyway for the support Mattia! 🙌