如何测试 Android ContentProvider 中抛出的异常
我正在尝试测试我的 contentprovider 的 getType 方法,特别是当传入无效的 uri 时。当前我抛出 IllegalArgumentException,但在我的测试中没有捕获异常。
这是我的测试
public void testIllegalArgumentExceptionThrownForInvalidUri() {
Uri badUri = Uri.parse("content://" + NoteProvider.AUTHORITY + "/somethingelse");
try {
String type = mockResolver.getType(badUri);
fail("No exception thrown");
} catch (Exception ex) {
assertEquals(IllegalArgumentException.class, ex.getCause().getClass());
}
}
和 getType 的实现,
@Override
public String getType(Uri uri) {
switch (uriMatcher.match(uri)) {
case URI_NOTES:
return Notes.CONTENT_TYPE;
case URI_NOTE_ID:
return Notes.CONTENT_ITEM_TYPE;
default:
throw new IllegalArgumentException("Unknown URI " + uri);
}
}
我已经单步执行了它并且可以看到抛出了异常,但在测试中调用的是 failed() 方法而不是 catch 块。
MockContentResolver 是否会吞掉异常?
免责声明:虽然我已经用 C# 编码很多年了,但我还是 android 和 java 的新手,所以我可能在做一些完全愚蠢的事情。 :D
I am trying to test the getType method of my contentprovider, particularly when an invalid uri is passed in. Currently I throw an IllegalArgumentException, but no exception is caught in my test.
Here is my test
public void testIllegalArgumentExceptionThrownForInvalidUri() {
Uri badUri = Uri.parse("content://" + NoteProvider.AUTHORITY + "/somethingelse");
try {
String type = mockResolver.getType(badUri);
fail("No exception thrown");
} catch (Exception ex) {
assertEquals(IllegalArgumentException.class, ex.getCause().getClass());
}
}
and the implementation of getType
@Override
public String getType(Uri uri) {
switch (uriMatcher.match(uri)) {
case URI_NOTES:
return Notes.CONTENT_TYPE;
case URI_NOTE_ID:
return Notes.CONTENT_ITEM_TYPE;
default:
throw new IllegalArgumentException("Unknown URI " + uri);
}
}
I have stepped through it and can see that the exception is thrown, but in the test the fail() method is being called instead of the catch block.
Does the MockContentResolver swallow exceptions?
Disclaimer: I am new to android and java although have been coding in C# for quite a few years now, so I may be doing something completely stupid. :D
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
请勿投掷。返回空值。根据 ContentResolver.getType() 的文档,
返回内容的 MIME 类型,如果 URL 无效或类型未知,则返回 null
Do not throw. Return null. Per ContentResolver.getType()'s documentation,
Returns A MIME type for the content, or null if the URL is invalid or the type is unknown