Android Room Test Delete不起作用(Java)

时间:2019-09-20 18:32:41

标签: java android testing android-room dao

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

我已经为测试尝试了几种不同的设置。没有一个起作用。

这是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列表为空之外,我没有,但不是。我在测试过程中仍然插入了目标。

1 个答案:

答案 0 :(得分:4)

@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