Content Provider JUnit Test and null getContext()



我正在尝试测试我的自定义内容提供程序的update()方法。由于 update() 方法中的 getContext() 方法调用为空,我收到空指针异常。为了缓解这个问题,我尝试实现为什么AndroidTestCase.getContext().getApplicationContext()返回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);
}

插入方法如下所示:

    @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;
}

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

所以问题的答案

是调用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);
}

相关内容

最新更新