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

savrov

09/11/2020, 12:43 PM
What is the best way to test abstract class? let’s say I have a class A
Copy code
abstract class A(param1: Param1, param2: Param2) {
  fun foo() {
    val param1result = param1.get()
    val param2result = param2.get()
    val result = calculateResult(param1result, param2)
  }
  
  abstract fun calculateResult(param1: Param1, param2: Param2): Smth
}
Now, I want to test it. But I can not create an instance of A, since its a abstract class. The only way I managed to make it work is to create a real A class and use spyk function:
Copy code
class AReal: A {
  override fun calculateResult(...) {
    ...
  }
}

class Test {
  val aReal = spyk(AReal(...., .....))
}
Is there any other better way?
b

bbaldino

09/11/2020, 3:57 PM
I'm pretty sure you can use a spyk on an abstract class
s

savrov

09/11/2020, 11:47 PM
but u can not call a contructor for abstract class) anymay, i did it loke this:
Copy code
private val useCase = spyk(UseCaseReal(mockk(), mockk()), recordPrivateCalls = true, block = {
        coEvery { abstartFun(any()) } returns smth
    })
b

bbaldino

09/11/2020, 11:49 PM
Why do you need to explicitly call the constructor?
you'd just do
val foo: MyAbstractClass = spyk()
10 Views