0

嘿!

我已经为我的应用程序编写了测试。我需要通过UI界面(使用robotium)将项目添加到数据库,然后我想使用SQLiteDatabase检查数据库中是否存在项目。

项目已成功添加(测试完成后我在数据库中看到新记录),但我的测试类中的 isExistsInDb 返回 false。我不明白为什么。请你帮助我好吗。谢谢!

活动类:

public abstract class EditActivity {


   // Some code .....

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        initButtonCancelOk();
    }

    protected void validateAndSave() {
        try {
            formValidator.validateAll();
            if (formValidator.isFormValid()) {
                DatabaseOpenHelper doh = new DatabaseOpenHelper(this);
                Dao d = new Dao(doh);
                d.add(fetchObjectFromUi());
                finish(); // destroy this activity
            } else {
                ToastImage.makeImageText(context,
                        R.drawable.warning,
                        formValidator.getMessages(),
                        Toast.LENGTH_SHORT
                    ).show();
            }
        } catch (Exception e) {
            Toast.makeText(context, " Error during validate form ", Toast.LENGTH_LONG).show();
            e.printStackTrace();
        }
    }

    private void initButtonCancelOk() {
        btnOk = (Button) findViewById(R.id.btn_ok);
        btnOk.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                validateAndSave();
            }
        });
    }    
}

测试类:

public class AddItemSmokeTest extends extends ActivityInstrumentationTestCase2<EditActivity> {

    protected Activity activity;
    protected Solo solo;

    public AddItemSmokeTest() {
        super("com.myapp", EditActivity.class);
        Intent i = createIntent(2);
        setActivityIntent(i);
        activity = getActivity();
        solo = new Solo(getInstrumentation(), activity);
        solo.sleep(1000); // interval between tests
    }

    protected Intent createIntent(long transType) {
        Intent i = new Intent();
        i.putExtra(INTENT_VALUE_MODE_NAME, MODE_INSERT_TRANSACTION);
        i.putExtra(INTENT_VALUE_TYPE_ID_NAME, transType);
        return i;
    }

    @Override
    protected void tearDown() throws Exception {

    }

    protected void setIncomExpenseData(AbsTransIncomeExpenseTestData testData) {
        solo.pressSpinnerItem(CATEGORY_SPN_INDEX, testData.getCategorySpinnerPos());
        solo.pressSpinnerItem(ACCOUNT_SPN_INDEX, testData.getAccountSpinnerPos());
        solo.typeText((EditText) activity.findViewById(com.rirdev.moneycounter.R.id.et_sum), testData.getSum());
        solo.typeText((EditText) activity.findViewById(com.rirdev.moneycounter.R.id.et_comment), testData.getComment());
    }

    @Smoke
    public void testAddIncomeTransaction() throws Exception {
        initForType(TransactionType.INCOME);
        AbsTransIncomeExpenseTestData testData = new IncomeTestData();
        setIncomExpenseData(testData);
        solo.clickOnButton(OK);
        //solo.getActivityMonitor();
        assertTrue( 
                    "Item" + testData.getComment() + " was not added ",
                    isExistsInDb(activity, Transactions.TABLE_NAME, Transactions.DESCRIPTION, testData.getComment())
                  );
    }

    protected static boolean isExistsInDb(Context context, String tableName, String commentFieldName, String comment) {

        DatabaseOpenHelper doh = new DatabaseOpenHelper(context);
        SQLiteDatabase db = doh.getDatabaseReadable();
        Cursor cursor = null;
        try {
            String query = "SELECT COUNT(*) FROM " + tableName + " WHERE " + commentFieldName + " = \"" + comment + "\"";
            cursor = db.rawQuery(query, null);
            cursor.moveToFirst();
            if (cursor.getInt(0) > 1) {
                return true;
            }
            return false;
        } finally {
            if (cursor != null) {
                cursor.close();
            }
            db.close();
            doh.close();
        }

    }

}

更新:

如果我第二次运行测试它会通过,因为在数据库中存在先前测试添加的项目。

4

2 回答 2

1

在 where clasue 中使用“string”而不是“string”.....

"SELECT COUNT(*) FROM " + tableName + " WHERE " + commentFieldName + " = '" + comment + "'";
于 2012-06-23T10:46:46.333 回答
1

我建议使用 use parametrized statement,你的方法很危险而且不太清楚。getCount()使用方法也更好。

String query = "SELECT COUNT(*) FROM " + tableName + " WHERE columnName = ?";
cursor = db.rawQuery(query, new Sring[] {comment});
int count = 0;
if (cursor.getCount() > 0) {
   cursor.moveToFirst();
   count = cursor.getInt(0);
}
if (count > 0) {
   return true;
}
else {
   return false;
}
于 2012-06-23T11:41:03.723 回答