首页 > 解决方案 > 同型号不相等

问题描述

我正在用 JUnitTest 覆盖我的应用程序来测试我的房间并作为文档

@Test
    public void writeCompanyAndReadInList() throws Exception {
        // Insert the company
        Company company = TestUtil.createCompany("MobOS2018");
        mCompanyDao.insertCompany(company);

        // Get the company
        LiveData<List<Company>> byName = mCompanyDao.getCompanies("MobOS2018 AND id =1");

        // Check if the two objects are equals
        assertEquals("Should be equal", byName.getValue().get(0), company);
    }

我的测试:

@Test
    public void writeUserAndReadInList() throws Exception {
    HistoryModel historyModel = TestUtil.createHistory(0,"21","3123",22-3-5L);
    mHistoryDao.save(historyModel);
    List<HistoryModel> byName = mHistoryDao.getAll();

    Log.e("-----------i", byName.get(0).getId()+" - "+historyModel.getId());
    Log.e("-----------d", byName.get(0).getDistance()+" - "+historyModel.getDistance());
    Log.e("-----------t", byName.get(0).getTime()+" - "+historyModel.getTime());
    Log.e("-----------c", byName.get(0).getCurrentTimeDate()+" - "+historyModel.getCurrentTimeDate());
    Log.e("-----------c", byName.get(0)+" - "+historyModel);
    Log.e("-----------eq", byName.get(0).toString().trim().equals(historyModel.toString().trim())+"");

    assertEquals(byName.get(0), historyModel);

日志是:

E/-----------i: 0 - 0
E/-----------d: 21 - 21
E/-----------t: 3123 - 3123
E/-----------c: 14 - 14
E/-----------c: com.fitnesstracker.model.HistoryModel@e803247 - com.fitnesstracker.model.HistoryModel@5d13a74
E/-----------eq: false

我已经记录了模型的所有字段并且它们是相等的,但是我不断收到它们不相等的错误(

java.lang.AssertionError: expected:<com.myApp.model.HistoryModel@e3b4c6e>
but was:<com.myApp.model.HistoryModel@b9d3f0f>

标签: javaandroidjunitjunit4junit5

解决方案


您需要覆盖hashCodeand equals,默认情况下,equals 基于内部对象 ID(相同引用)。

存储和加载的对象不是同一个引用。它们是具有相同值的两个不同对象,但您没有定义覆盖等于,这应该被视为等于而不是基于引用检查。


推荐阅读