DbAdapter implements StorageService { public int count(Table table) { int n = 0; SQLiteDatabase db = null; try { db = mDb.getReadableDatabase(); String qs = "SELECT COUNT(*) FROM " + REPORTS_TABLE; if (table != null) { qs += " WHERE "+KEY_TABLE+" = ?"; } SQLiteStatement stmt = db.compileStatement(qs); if (table != null) { stmt.bindString(1,table.name); } n = (int)stmt.simpleQueryForLong(); } catch (final SQLiteException e) { Logger.log(TAG, "Failed to count records in table: " + table.name, Logger.SDK_DEBUG); mDb.delete(); } finally { if (null != db) db.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 countSuccess() { SQLiteStatement stmt = mock(SQLiteStatement.class); SQLiteDatabase db = mock(SQLiteDatabase.class); when(db.compileStatement(anyString())).thenReturn(stmt); when(stmt.simpleQueryForLong()).thenReturn(10L); when(handler.getReadableDatabase()).thenReturn(db); assertEquals(adapter.count(table), 10); verify(db, times(1)).close(); }
@Test public void countFailed() { SQLiteStatement stmt = mock(SQLiteStatement.class); SQLiteDatabase db = mock(SQLiteDatabase.class); when(db.compileStatement(anyString())).thenThrow(new SQLiteException()); when(handler.getReadableDatabase()).thenReturn(db); assertEquals(adapter.count(table), 0); verify(db, times(1)).close(); verify(handler, times(1)).delete(); }