jeudi 27 août 2015

Why does .equals() result in an Assertion Error when comparing two objects...but only sometimes?

I'm working on unit testing for a project at code school and .equals() is giving me some trouble. In my project, .save() is saving into a sql database. This code passes the 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));
}

Why can .equals() compare some objects and not others? In my code example, the only difference I'm seeing is that one object takes one parameter, and the other takes two.

Thank you!

Aucun commentaire:

Enregistrer un commentaire