Android 房间测试删除不起作用 (Java)

Android Room Test Delete Not Working (Java)

我正在尝试使用 android-room 对我的 DAO 进行单元测试。我写了一个正常工作的插入测试。不幸的是,删除方法似乎不起作用。

我已经尝试了几种不同的测试设置。 None 成功了。

这是 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();
}

这是每月实体:

@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;
    }

这是我的测试 运行:

@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());
    }

我除了 updatedGoals 列表为空,但事实并非如此。还有我测试时插入的目标。

注释为@Delete的方法使用实体上的主键来知道要从数据库中删除哪一行(因为可能有多行具有相同的数据但不同的键)。

但是,您使用的是您创建的初始 goal 对象,该对象 没有主键 ,因此不能用于指示要删除的行.

尝试这样做:

monthlyDao.save(goal);
List<Monthly> goals = monthlyDao.findAllList();
Assert.assertThat(goals.get(0).getTitle(), equalTo(goal.getTitle()));
monthlyDao.delete(goals.get(0)); // <-- Delete the goal returned from the find, which will have an ID
List<Monthly> updatedGoals = monthlyDao.findAllList();
Assert.assertTrue(updatedGoals.isEmpty());

这可以很容易地清理一下,但上面的示例只更改了一行,以明确问题出在哪里。

有关文档,请参阅 here