DbAdapter implements StorageService { public int addEvent(Table table, String data) { if (!this.belowDatabaseLimit()) { Logger.log(TAG, "Database file is above the limit", Logger.SDK_DEBUG); vacuum(); } int n = 0; try { SQLiteDatabase db = mDb.getWritableDatabase(); ContentValues cv = new ContentValues(); cv.put(KEY_TABLE, table.name); cv.put(KEY_DATA, data); cv.put(KEY_CREATED_AT, System.currentTimeMillis()); db.insert(REPORTS_TABLE, null, cv); String countQuery="SELECT COUNT(*) FROM "+ REPORTS_TABLE+" WHERE "+KEY_TABLE+"=?"; SQLiteStatement countStmt = db.compileStatement(countQuery); countStmt.bindString(1, table.name); n=(int)countStmt.simpleQueryForLong(); if (n == 1) { cv = new ContentValues(); cv.put(KEY_TABLE, table.name); cv.put(KEY_TOKEN, table.token); db.insertWithOnConflict(TABLES_TABLE, null, cv, SQLiteDatabase.CONFLICT_IGNORE); } } catch (final SQLiteException e) { Logger.log(TAG, "Failed to insert event to 'records' table", Logger.SDK_DEBUG); mDb.delete(); } finally { mDb.close(); } return n; } DbAdapter(Context context); static DbAdapter getInstance(Context context); int addEvent(Table table, String data); int count(Table table); Batch getEvents(Table table, int limit); List<Table> getTables(); int deleteEvents(Table table, String lastId); void deleteTable(Table table); void vacuum(); static final String KEY_DATA; static final String KEY_TOKEN; static final String KEY_TABLE; static final String KEY_CREATED_AT; static final String TABLES_TABLE; static final String REPORTS_TABLE; }
@Test public void addEvent1() { SQLiteStatement stmt = mock(SQLiteStatement.class); when(stmt.simpleQueryForLong()).thenReturn(29L); SQLiteDatabase db = mock(SQLiteDatabase.class); when(handler.getWritableDatabase()).thenReturn(db); when(db.compileStatement(anyString())).thenReturn(stmt); assertEquals(adapter.addEvent(table, "foo bar"), 29); verify(db, times(1)).insert(eq(DbAdapter.REPORTS_TABLE), isNull(String.class), any(ContentValues.class)); }
@Test public void addEvent2() { SQLiteStatement stmt = mock(SQLiteStatement.class); when(stmt.simpleQueryForLong()).thenReturn(1L); SQLiteDatabase db = mock(SQLiteDatabase.class); when(handler.getWritableDatabase()).thenReturn(db); when(db.compileStatement(anyString())).thenReturn(stmt); adapter.addEvent(table, "foo bar"); verify(db, times(1)).insert(eq(DbAdapter.REPORTS_TABLE), isNull(String.class), any(ContentValues.class)); verify(db, times(1)).insertWithOnConflict(eq(DbAdapter.TABLES_TABLE), isNull(String.class), any(ContentValues.class), eq(SQLiteDatabase.CONFLICT_IGNORE)); }