I have an interface and two objects implementing that interface, massively simplied;
public interface MyInterface {
public int getId();
public int getName();
...
}
public class A implements MyInterface {
...
}
public class B implements MyInterface {
...
}
We are migrating from using one implementation to the other but I need to check that the objects of type B that are generated are equivalent to those of type A. Specifically I mean that for all of the interface methods an object of Type A and Type B will return the same value (I’m just checking my code for generating this objects is correct).
How would you go about this?
Map<String, MyInterface> oldGeneratedObjects = getOldGeneratedObjects();
Map<String, MyInterface> newGeneratedObjects = getNewGeneratedObjects();
// TODO: Establish that for each Key the Values in the two maps return equivalent values.
I’m looking for good coding practices and style here. I appreciate that I could just iterate through one key set pulling out both objects which should be equivalent and then just call all the methods and compare, I’m just thinking there may be a cleaner, more extensible way and I’m interested to learn what options there might be.
Would it be appropriate / possible / advised to override equals or implement Comparable?
Thanks in advance,
Gavin
I would implement a custom version of
equalsin the test class, not inside any of those implementation classes (since it would clash with the regularequalscontract). Something like:I understand that this check would be required only during the migration period, so the normal
equalsmethods of each implementation should not be affected by this. Namely,A.equalsshould only returntruefor an equal instance ofA, and should always returnfalsefor an instance ofB. And vice versa.Once the migration is over, you no longer need class A neither the tester class, and you can continue using class B without needing to touch its implementation.
Note that if
MyInterface(orAandB) extendsComparable, you should also test that the implementations inAandBare equivalent.(And you surely know that if you implement
equalsyou must also implementhashCode.)