我在我的Dagger2项目中使用KeyStoreKeyGenerator(来自in.co.ophio.secure),并且我想使用Robolectric测试我的片段。
我向演示者注入(inject)片段。演示者已注入(inject)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吗?我应该使用接口(interface)包装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)