Reputation: 769
I'm using in my project Dagger2, KeyStoreKeyGenerator (from in.co.ophio.secure) and I want to use Robolectric to test my Fragment.
I inject presenter to my Fragment. Presenter has userPrefs injected. UserPrefs have KeyStoreKeyGenerator implemented
class UserPreferences(val application: App) : UserPreferencesAPI {
// another methods and fields
private val keyGenerator = KeyStoreKeyGenerator.get(application, application.packageName)
}
this is my presenter
class MainPresenter(...,
val sharedPreference: UserPreferencesAPI)
and this is my test
private MainFragment fragment;
private MainActivity activity;
@Before
public void setUp() {
activity = Robolectric.buildActivity(MainActivity.class).create().start().resume().get();
fragment = MainFragment.Companion.newInstance();
}
@Test
public void shouldBeNotNull() {
Assertions.assertThat(activity).isNotNull();
}
After running test I see:
java.lang.NullPointerException
at android.security.KeyStore.isHardwareBacked(KeyStore.java:318)
at android.security.KeyChain.isBoundKeyAlgorithm(KeyChain.java:397)
at in.co.ophio.secure.core.KeyStoreKeyGenerator.<init>(KeyStoreKeyGenerator.java:41)
at in.co.ophio.secure.core.KeyStoreKeyGenerator.get(KeyStoreKeyGenerator.java:56)
at unofficial.coderoid.wykop.newapp.utils.UserPreferences.<init>(UserPreferences.kt:24)
Should I create shadow KeyStoreKeyGenerator? Should I wrap KeyStore class using interface?
Upvotes: 3
Views: 668
Reputation: 970
I manage to solve it by writing a custom shadow http://robolectric.org/custom-shadows/
@Implements(android.security.KeyChain.class)
public class KeyChainShadow {
@RealObject
private KeyChain keyChain;
@Implementation
public static boolean isBoundKeyAlgorithm(String algorithm) {
return false;
}
}
don't forget to annotate your test with
@Config(shadows = KeyChainShadow.class)
Upvotes: 1