【问题标题】:The same model is not equal同型号不相等
【发布时间】:2020-03-07 16:16:39
【问题描述】:

我正在使用 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>

【问题讨论】:

    标签: java android junit junit4 junit5


    【解决方案1】:

    你需要覆盖hashCodeequals,默认情况下equals是基于内部对象ID(同参考)。

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

    【讨论】:

      猜你喜欢
      • 2018-01-02
      • 2022-01-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-02-21
      • 2017-07-02
      • 2019-02-11
      • 1970-01-01
      相关资源
      最近更新 更多