I am working on a basic spring boot application. I am integration testing my create and read functionality and am struggling with the isEqualTo method. It is failing because the objects are two different instances of class Fruit. However, they are identical in all values except memory address. This is because I use “new” in my RowMapper. How can I avoid using new with the RowMapper class?
Code is below:
From test:
public void testThatFruitCanBeCreatedAndFound() {
Fruit f = TestDataUtil.buildFruitA();
underTest.create(f);
Optional<Fruit> result = underTest.read(f.getID());
assertThat(result).isPresent();
// This assertion fails
assertThat(result.get()).isEqualTo(f);
// Assertions below pass
// assertThat(result.get().getName()).isEqualTo(f.getName());
// assertThat(result.get().getFruitClass()).isEqualTo(f.getFruitClass());
// assertThat(result.get().getAge()).isEqualTo(f.getAge());
// assertThat(result.get().getID()).isEqualTo(f.getID());
}
From DAO Class:
public Optional<Fruit> read(long id) {
List<Fruit> results = jdbcTemplate.query(
"SELECT id, name, fruitClass, age FROM "fruit" WHERE id = ? LIMIT 1",
new FruitRowMapper(), id);
return results.stream().findFirst();
};
public static class FruitRowMapper implements RowMapper<Fruit> {
@Override
public Fruit mapRow(ResultSet rs, int rowNum) throws SQLException {
return new FruitBuilder(rs.getString("name"))
.id(rs.getLong("id"))
.fruitClass(FruitClass.valueOf(rs.getString("fruitClass")))
.age(rs.getInt("age"))
.build();
}
}
From FruitBuilder:
public Fruit build() {
return new Fruit(name, fruitClass, id, age);
}
Any help would be greatly appreciated! I am going to continue to try and figure out how to remove new keyword.
psc3245 is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.