I am working on unit testing a project in a code school, and .equals() gives me some problems. In my project, .save() stored in the SQL database. This code passes unit test:
@Test public void save_assignsNameToObject() { Restaurant testRestaurant = new Restaurant("PokPok","503-444-4444"); testRestaurant.save(); Restaurant savedRestaurant = Restaurant.all.get(0); assertEquals(savedRestaurant.getName(), "PokPok"); }
But if I change the final line to the following, it will result in an assertion error:
assertTrue(savedRestaurant.equals(testRestaurant));
I debugged using System.out.println() to verify that both values ββin testRestaurant do ".equal" the corresponding values ββin savedRestaurant . The following unit test (for an object of another, very similar class) passes using the .equals() method:
@Test public void save_assignsIdToObject_true() { Cuisine testCuisine = new Cuisine("Mexican"); testCuisine.save(); Cuisine savedCuisine = Cuisine.all().get(0); assertTrue(savedCuisine.equals(testCuisine)); }
Edit: here is my source code for .equals() :
@Override public boolean equals(Object otherRestaurant) { if (!(otherRestaurant instanceof Restaurant)) { return false; } else { Restaurant newRestaurant = (Restaurant) otherRestaurant; return this.getId() == new Restaurant.getId() && this.getName().equals(newRestaurant.getName()) && ... this.getPhone().equals(newRestaurant.getPhone()); } }
Why can .equals() compare some objects and not others? In my code example, the only difference I see is that one object takes one parameter and the other takes two.
Thanks!
source share