在 Robolectric 测试中使用 Android KeyStore
我正在尝试编写一些针对 Android 密钥库 的测试用例。但是,当我编写以下测试用例时:
@RunWith(RobolectricGradleTestRunner.class)
@Config(constants = BuildConfig.class, sdk = 21)
public class FancyPantsUnitTest {
@Test
public void buildKey() {
keyPairGenerator = KeyPairGenerator.getInstance("RSA", "AndroidKeyStore");
keyPairGenerator.initialize(4096);
final KeyPair keyPair = keyPairGenerator.generateKeyPair();
}
}
这会失败,但有以下例外:
org.junit.ComparisonFailure: expected:<null> but was:<java.security.KeyStoreException: AndroidKeyStore not found>
我的目标是 API 级别 23(如果有帮助的话)。
I'm attempting to write a few testcases that work against the Android Keystore. However, when I write the following test case:
@RunWith(RobolectricGradleTestRunner.class)
@Config(constants = BuildConfig.class, sdk = 21)
public class FancyPantsUnitTest {
@Test
public void buildKey() {
keyPairGenerator = KeyPairGenerator.getInstance("RSA", "AndroidKeyStore");
keyPairGenerator.initialize(4096);
final KeyPair keyPair = keyPairGenerator.generateKeyPair();
}
}
This fails with the following exception:
org.junit.ComparisonFailure: expected:<null> but was:<java.security.KeyStoreException: AndroidKeyStore not found>
I'm targeting API Level 23 if that helps.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
Matthew Dolan 在他的文章中提出了一个出色的解决方案。
以下是创建
FakeAndroidKeyStore
的代码,在调用
java.security.KeyStore
之前使用。在示例中:
Matthew Dolan came up with an outstanding solution in his article.
Here is the code to create a
FakeAndroidKeyStore
Use just before where the
java.security.KeyStore
gets called.In example:
https://github.com/robolectric/robolectric/issues/1518 已经对此进行了讨论。
简而言之:
尝试 PowerMockito 时也会发生同样的情况。
There is already a discussion on this at https://github.com/robolectric/robolectric/issues/1518 .
In short:
The same happens when trying PowerMockito.
您可以模拟 KeyStore 及其行为。这是一个代码示例
You can mock KeyStore and its behavior. Here is a code example