I've problems writing a test implementation for an...
# announcements
i
I've problems writing a test implementation for an interface:
Copy code
interface Preferences {
    // ...
    fun <T> putObject(key: PreferencesKey, model: T?)
    fun <T> getObject(key: PreferencesKey, clazz: Class<T>): T?
}
Force returning a specific object, for unit testing
Copy code
class PreferencesReturningObject<T>(val obj: T): Preferences {
    override fun <T> putObject(key: PreferencesKey, model: T?) {}
    override fun <T> getObject(key: PreferencesKey, clazz: Class<T>): T? = obj
}
How can I write this? (Without using Mockito or similar) Edit: It's "fixed" by writing
obj as T
(the class type parameter actually doesn't make sense, it can be just
Any
) but wonder if there's a better way
b
Did you intend to put the
<T>
on the
Preferences
declaration? I.e.:
Copy code
interface Preferences<T>
What’s happening in your test implementation is that the
<T>
in
PreferencesReturningObject<T>
is being hidden by the functions’
<T>
declaration, so the
<T>
from the class is not the same as the
<T>
being returned by the function. Put differently, with your current code, this would compile, but fail at runtime:
Copy code
val prefs = PreferencesReturningObject<String>("hello")
val number = prefs.getObject<Int>(PreferencesKey("mykey"), Int::class.java)
If the
<T>
on the functions is supposed to be different per-key, then yes, the way you’ve mocked it out is the best way of doing it without using a mocking library. However, if you’re expecting every preference value to have the same type, you should move
<T>
to the
Preferences
interface and remove the declaration from the functions.
👆 2