iex
05/06/2020, 3:29 PMinterface 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
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 wayBrian Saltz Jr
05/06/2020, 3:44 PM<T>
on the Preferences
declaration? I.e.:
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:
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.