为SQLite编写TestCase的问题。
我试着写下一个测试,但它崩溃了。
Android Studio在以下代码中的两个错误行上显示错误java.lang.UnsupportedOperationException。也许有人可以告诉我哪里出错了。
public class DeviceDatabase {
private SQLiteDatabase db;
private DeviceSQLiteHelper dbHelper;
/**
* Constructor
*
* @param context
*/
public DeviceDatabase(Context context) {
dbHelper = new DeviceSQLiteHelper(context);
db = dbHelper.getWritableDatabase();
}
/**
* close sqlite database
*/
public void close() {
db.close();
}
/**
* Create new device
* @param
*/
public boolean createDevice(String bt_name, String bt_addr, String bdx_name) {
ContentValues contentValues = new ContentValues();
contentValues.put(DeviceSQLiteHelper.BT_NAME, bt_name);
contentValues.put(DeviceSQLiteHelper.BT_ADDR, bt_addr);
contentValues.put(DeviceSQLiteHelper.BDX_NAME, bdx_name);
// Insert into DB
long result = db.insert(DeviceSQLiteHelper.TABLE_NAME, null, contentValues);
if (result != 0 )
return true;
else
return false;
}
...
带有MockContext的Test类。老实说,我不知道它可以这样使用。
public class DeviceListControlTest {
String bt_addr = "00:01:02:03:03:08";
public DeviceDatabase mDeviceDatabase;
public MockContext mMockContext;
@Before
public void setUp() throws Exception {
// need mock context
mMockContext = new MockContext();
mDeviceDatabase = new DeviceDatabase(mMockContext); // error
}
@Test
public void testCreateDevice() throws Exception {
mDeviceDatabase.createDevice("Hamburg", bt_addr, "HamburgBT");
List<DeviceName> deviceNameList;
deviceNameList = mDeviceDatabase.getDevices();
boolean result = checkItem(deviceNameList, bt_addr);
assertThat(true, is(equalTo(result)));
}
....
答案 0 :(得分:0)
当您在计算机上运行单元测试时(不在Android设备/模拟器本身上),使用Android SDK的存根版本,每次调用任何方法时都会抛出UnsupportedOperationException
。
你有两个(好的)选择: