内容提供者JUnit Test和null getContext()

时间:2012-06-21 02:24:35

标签: java android nullpointerexception android-contentprovider

我正在尝试测试自定义内容提供程序的update()方法。我收到一个空指针异常,因为update()方法中的getContext()方法调用为null。为了缓解这个问题,我尝试实施Why does AndroidTestCase.getContext().getApplicationContext() return null?无济于事。我的测试类如下所示:

 public class AddressContentProviderTest extends ProviderTestCase2<AddressContentProvider> {

    public AddressContentProviderTest() {
    super(AddressContentProvider.class, AddressContentProvider.class.getName());
}

protected void setUp() throws Exception {
    super.setUp();
}
    public void testInsert() {
         Uri CONTENT_URI = Uri.parse("content://" + AddressContentProvider.AUTHORITY + "/address");
         AddressContentProvider addressContentProvider = new AddressContentProvider();
         ContentValues initialValues = new ContentValues();
         boolean isException = false;
         Uri returnURI = null;
         initialValues.put("country", "test");
         initialValues.put("region", "test");
         initialValues.put("city", "test");
         initialValues.put("state", "FL");
         initialValues.put("zip", "90210");
         initialValues.put("province", "test");
         initialValues.put("geo_location_id", "");

          returnURI = addressContentProvider.insert(CONTENT_URI, initialValues);

     assertTrue(returnURI != null);

}

insert方法如下所示:

    @Override
    public int update(Uri uri, ContentValues values, String where, String[]  whereArgs) {
           SQLiteDatabase db =dbHelper.getWritableDatabase();
           int count;

          switch (sUriMatcher.match(uri)) {
            case ADDRESS:
                count = db.update(ADDRESS_TABLE_NAME, values, where, whereArgs);
                break;
            default:
         throw new IllegalArgumentException("Unknown URI " + uri);
    }
    getContext().getContentResolver().notifyChange(uri, null);
    return count;
}

我在平台10上使用Android 2.3.3运行我的测试。

1 个答案:

答案 0 :(得分:0)

所以问题的答案是调用getProvider();方法。这使我可以访问执行线程中的AddressContentProvider;

    public void testInsert() {
        Uri CONTENT_URI = Uri.parse("content://" + AddressContentProvider.AUTHORITY + "/address");
        AddressContentProvider addressContentProvider = getProvider();
        ContentValues initialValues = new ContentValues();
    //Uri returnURI = null;
        initialValues.put("country", "USA");
        initialValues.put("region", "test");
        initialValues.put("city", "Jacksonville");
        initialValues.put("state", "FL");
        initialValues.put("zip", "32258");
        initialValues.put("province", "test");
        initialValues.put("geo_location_id", "");
        Uri returnURI = addressContentProvider.insert(CONTENT_URI, initialValues);
        assertTrue(returnURI != null);
}