Robolectric KeyStoreKeyGenerator

我正在使用我的项目Dagger2,KeyStoreKeyGenerator(来自in.co.ophio.secure),我想用Robolectric来测试我的片段。

我将主持人注入我的片段。 Presenter已注入userPrefs。 UserPrefs已经实现了KeyStoreKeyGenerator

class UserPreferences(val application: App) : UserPreferencesAPI { // another methods and fields private val keyGenerator = KeyStoreKeyGenerator.get(application, application.packageName) } 

这是我的主持人

  class MainPresenter(..., val sharedPreference: UserPreferencesAPI) 

这是我的考验

 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(); } 

运行测试后,我看到:

 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) 

我应该创建阴影KeyStoreKeyGenerator? 我应该使用接口封装KeyStore类吗?

我设法解决它通过写一个自定义的影子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; } } 

不要忘记用你的测试注释

 @Config(shadows = KeyChainShadow.class)