vendredi 20 septembre 2019

Android Room Test Delete Not Working (Java)

I'm trying to unit-test my DAO using android-room. I have written an insert test that works properly. Unfortunately, the delete method doesn't seem to be working.

I've tried a few different setups for the test. None have worked.

Here is the DAO:

@Dao
public interface MonthlyDao {

    @Insert(onConflict = OnConflictStrategy.REPLACE)
    void saveAll(List<Monthly> goals);

    @Insert(onConflict = OnConflictStrategy.REPLACE)
    void save(Monthly goal);

    @Update
    void update(Monthly goal);

    @Delete
    void delete(Monthly goal);

    @Query("SELECT * FROM Monthly")
    LiveData<List<Monthly>> findAll();

    @Query("SELECT * FROM monthly")
    List<Monthly> findAllList();
}

Here is the Monthly entity:

@Entity
public class Monthly {
    @PrimaryKey(autoGenerate = true)
    private int monthlyId;

    @TypeConverters(CalendarTypeConverter.class)
    @ColumnInfo(name = "date")
    private Calendar date = Calendar.getInstance();

    @ColumnInfo(name = "title")
    private String title;

    @ColumnInfo(name = "description")
    private String description;

    @ColumnInfo(name = "completed")
    private boolean completed;
...
    public int getMonthlyId() {
        return monthlyId;
    }

    public void setMonthlyId(int monthlyId) {
        this.monthlyId = monthlyId;
    }

And here is the test I am running:

@RunWith(AndroidJUnit4.class)
public class MonthlyTest {
    private MonthlyDao monthlyDao;
    private MonthlyGoalsDatabase db;

    @Before
    public void createDb() {
        Context context = ApplicationProvider.getApplicationContext();
        db = Room.inMemoryDatabaseBuilder(context, MonthlyGoalsDatabase.class).build();
        monthlyDao = db.getMonthlyDao();
    }

    @After
    public void closeDb() throws IOException {
        db.close();
    }

    @Test
    public void deleteGoal() throws Exception {
        String title = "test delete title";
        Calendar date = Calendar.getInstance();
        date.set(Calendar.HOUR_OF_DAY, 0);
        String desc = "test delete desc";
        Monthly goal = new Monthly(title, date, desc);
        monthlyDao.save(goal);
        List<Monthly> goals = monthlyDao.findAllList();
        Assert.assertThat(goals.get(0).getTitle(), equalTo(goal.getTitle()));
        monthlyDao.delete(goal);
        List<Monthly> updatedGoals = monthlyDao.findAllList();
        Assert.assertTrue(updatedGoals.isEmpty());
    }

I except the updatedGoals list to be empty, but it isn't. There is still the goal that I inserted during the test.

Aucun commentaire:

Enregistrer un commentaire