https://kotlinlang.org logo
#android
Title
# android
l

Long Tran

10/09/2023, 9:27 AM
Hi everyone, I’m dealing with an issue when trying to spy my class contains a value class inside the constructor with
spyk
which provided by
Mockk
The code as below:
Copy code
@JvmInline
value class MyValueClass(Val value: String = “”) : Serializable

class A(
   Val valueClass: MyValueClass = MyValueClass()
)

// In unit test file
@Test
fun test() {
    Val mockClass = spyk<A>()
    …
}
And this error happened
Copy code
io.mockk.MockKException: Can't instantiate proxy via default constructor for class A
Appreciate with your help 🙏
p

Pablichjenkov

10/09/2023, 10:24 AM
I haven't used mockk in quite a bit of time but I believe spyk receives an instance. Create the A() instance and pass it to spyk()
l

Long Tran

10/09/2023, 3:07 PM
It works, thanks @Pablichjenkov 🙌 Although I don’t understand why this way works 🤷‍♂️ Can anyone help explain it, please 🙏
p

Pablichjenkov

10/09/2023, 3:12 PM
Is the purpose of a spy. In a spy you provide an implementation with actual functions and mock part of it, a few of them. In contrast, a mock, mocks the full class functions.
You can research more on mock vs spy
l

Long Tran

10/09/2023, 3:38 PM
Yup, I understand about the mock and spy. Just don’t know why in my case spy(A()) works and spyk<A>() doesn’t
In the
MockK
document, they have the same meaning in the case of the default constructor tho
p

Pablichjenkov

10/09/2023, 4:25 PM
I got you now, humm, is probably due to the way it works internal. Mocking/spying an interface or abstract or open class may be based on implementing an instance of these 3. But since the class is final the library is not able to extend it. I guess is related to that but maybe was a design decision.
39 Views