2016-10-22 58 views
3

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

我将主持人注入我的片段。 Presenter已注入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类吗?

回答

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) 
来注释测试