Marc Knaup
06/03/2021, 6:16 PMabstract
functions and properties. If an unimplemented one is called it throws a NotImplementedError
.
Ex. unit test for `FooCreator`:
interface FooRepository {
fun add(foo: Foo)
fun get(id: String): Foo?
fun delete(id: String)
}
var actual: Foo? = null
val creator = FooCreator(repository = test object : FooRepository {
override fun add(foo: Foo) {
assertNull(actual)
actual = foo
}
})
creator.create(id = "bar")
assertEquals(actual, Foo(id = "bar"))
Alternatively full-fledged mocking of abstract funs/props and setters to set/unset each implementation.ephemient
06/03/2021, 7:05 PMmockk
can do this, and even without it,
inline fun <reified T: Any> stub(): T = java.lang.reflect.Proxy.newProxyInstance(T::class.java.classLoader, arrayOf(T::class.java)) { _, method, _ -> throw NotImplementedError("stub: $method") } as T
object : FooRepository by stub() {
override fun add(foo: Foo) {
// ...
}
}
works on JVM with no dependenciesMarc Knaup
06/03/2021, 7:05 PMephemient
06/03/2021, 7:07 PMspand
06/04/2021, 7:12 AMProxy
-like which (as @ephemient shows) makes it quite easy to implement oneself.mikehearn
06/04/2021, 12:06 PMMarc Knaup
06/04/2021, 1:25 PMephemient
06/04/2021, 1:29 PMephemient
06/04/2021, 2:42 PMMarc Knaup
06/04/2021, 2:44 PMedrd
06/04/2021, 7:44 PMinline fun <reified T> mock(): T = error("Implemented by compiler plugin")
interface Hello {
fun a()
fun b()
fun c()
}
var actual: Foo? = null
val creator = FooCreator(repository = object : FooRepository by mock() {
override fun add(foo: Foo) {
assertNull(actual)
actual = foo
}
})
Where calls to mock()
would be replaced with objects implementing the interfacegildor
06/08/2021, 7:54 AM