DbAdapter implements StorageService { public Batch getEvents(Table table, int limit) { Cursor c = null; String lastId = null; List<String> events = null; try { final SQLiteDatabase db = mDb.getReadableDatabase(); String whereParams=KEY_TABLE+"=?"; String orderParam = KEY_CREATED_AT+" ASC"; c = db.query(REPORTS_TABLE, null, whereParams, new String[]{table.name}, null, null, orderParam, String.valueOf(limit)); events = new ArrayList<>(); while (c.moveToNext()) { if (c.isLast()) { lastId = c.getString(c.getColumnIndex(REPORTS_TABLE + "_id")); } events.add(c.getString(c.getColumnIndex(KEY_DATA))); } } catch (final SQLiteException e) { Logger.log(TAG, "Failed to get a events of table" + table.name, Logger.SDK_DEBUG); lastId = null; events = null; } finally { if (null != c) c.close(); mDb.close(); } if (lastId != null && events != null) { return new Batch(lastId, events); } return null; } 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 getEvents() { Cursor cursor = mock(Cursor.class); SQLiteDatabase db = mock(SQLiteDatabase.class); when(db.query(anyString(), any(String[].class), anyString(), any(String[].class), anyString(),anyString(), anyString(), anyString())).thenReturn(cursor); when(handler.getReadableDatabase()).thenReturn(db); when(cursor.moveToNext()).thenReturn(true, true, false); when(cursor.isLast()).thenReturn(false, true); when(cursor.getString(anyInt())).thenReturn("foo", "2", "bar"); Batch batch = adapter.getEvents(table, 1); assertEquals(batch.events.toString(), "[foo, bar]"); assertEquals(batch.lastId, "2"); }