Search code examples
javaandroidandroid-contentprovider

How to test exception thrown in Android ContentProvider


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


Solution

  • 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