Java 内容提供程序JUnit测试和null getContext()
我正在尝试测试自定义内容提供程序的update()方法。由于update()方法中的getContext()方法调用为null,我收到一个null指针异常。为了缓解这个问题,我尝试了实施,但没有效果。我的测试类如下所示:Java 内容提供程序JUnit测试和null getContext(),java,android,nullpointerexception,android-contentprovider,Java,Android,Nullpointerexception,Android Contentprovider,我正在尝试测试自定义内容提供程序的update()方法。由于update()方法中的getContext()方法调用为null,我收到一个null指针异常。为了缓解这个问题,我尝试了实施,但没有效果。我的测试类如下所示: public class AddressContentProviderTest extends ProviderTestCase2<AddressContentProvider> { public AddressContentProviderTest()
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;
}
我正在使用Android 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);
}