【问题标题】:Robolectric KeyStoreKeyGeneratorRobolectric KeyStoreKeyGenerator
【发布时间】:2016-10-22 12:41:14
【问题描述】:

我在我的项目 Dagger2 中使用 KeyStoreKeyGenerator(来自 in.co.ophio.secure)并且我想使用 Robolectric 来测试我的 Fragment。

我将演示者注入到我的片段中。 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 类吗?

【问题讨论】:

    标签: java android kotlin robolectric


    【解决方案1】:

    我设法通过编写自定义阴影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)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-12-29
      • 2016-09-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多