From fb7abb44e0ad5f1f381033d148e34ac1a8988168 Mon Sep 17 00:00:00 2001 From: Rob Bygrave Date: Fri, 25 Apr 2014 19:23:56 +1200 Subject: [PATCH] Add a test for enhancement equals() and hashCode() --- .../enhancement/TestEnhancementEquals.java | 56 +++++++++++++++++++ 1 file changed, 56 insertions(+) create mode 100644 src/test/java/com/avaje/tests/enhancement/TestEnhancementEquals.java diff --git a/src/test/java/com/avaje/tests/enhancement/TestEnhancementEquals.java b/src/test/java/com/avaje/tests/enhancement/TestEnhancementEquals.java new file mode 100644 index 000000000..c7b8b77f3 --- /dev/null +++ b/src/test/java/com/avaje/tests/enhancement/TestEnhancementEquals.java @@ -0,0 +1,56 @@ +package com.avaje.tests.enhancement; + +import junit.framework.Assert; + +import org.junit.Test; + +import com.avaje.ebean.BaseTestCase; +import com.avaje.tests.model.basic.Product; + +/** + * Note take care if you run this test in an IDE with a debugger as that can trigger the equals and + * hashCode (and the identity value can get populated un-normally). + */ +public class TestEnhancementEquals extends BaseTestCase { + + + @Test + public void testEqualsBasedOnIdValue() { + + Product product1 = new Product(); + product1.setId(345); + product1.setName("blah"); + + Product product2 = new Product(); + product2.setId(345); + + Assert.assertEquals("equal based on id", product1, product2); + Assert.assertEquals("hashCode equal based on id", product1.hashCode(), product2.hashCode()); + + product2.setName("kumera"); + Assert.assertEquals("still equal based on identity", product1, product2); + Assert.assertEquals("still hashCode equal based on id", product1.hashCode(), product2.hashCode()); + } + + + @Test + public void testWhenEqualsTouchedFirst() { + + Product product1 = new Product(); + product1.setName("blah"); + int hashcode1 = product1.hashCode(); + + // equals has been called so the hashCode and 'identity' has been baked in + product1.setId(345); + int hashcode2 = product1.hashCode(); + + Assert.assertEquals("hashCode can't change",hashcode1, hashcode2); + + Product product2 = new Product(); + product2.setId(345); + + Assert.assertFalse("Not equal now", product1.equals(product2)); + Assert.assertTrue("Different hashCode", product1.hashCode() != product2.hashCode()); + } + +}