If we want to test an extension function on a type, we can create an instance of this type, call the function and check the returned value. But what about testing extension functions defined inside classes?
abstract class AbstractClass<T> {
fun doStuff(): T = "Hello".foo()
abstract fun String.foo(): T
}
class SubClass1: AbstractClass<Int>() {
override fun String.foo(): Int = 1
}
class SubClass2: AbstractClass<Boolean>() {
override fun String.foo(): Boolean = true
}
How do we test the logic of the methods foo() in classes SubClass1 and SubClass2? Is it even possible?
I know I can change the design to test it. Two possibilities have occurred to me:
Don't use extension functions. ¯\_(ツ)_/¯
abstract class AbstractClass<T> { fun doStuff(): T = foo("Hello") abstract fun foo(string: String): T } class SubClass1: AbstractClass<Int>() { override fun foo(string: String): Int = 1 }Then we can create an object
SubClass1, callfoo()and check the returned value.Create additional extension functions with
internalvisibility just to test the logic.class SubClass1: AbstractClass<Int>() { override fun String.foo(): Int = internalFoo() } internal fun String.internalFoo(): Int = 1Then we can create an object
String, callinternalFoo()and check the returned value. However, I don't like this solution because we could change the body ofoverride fun String.foo(): Intand our test would pass.
So, is it possible to test extension functions inside classes? If not, how would you change your design in order to test their logic?