java - Unit testing - implementing equals only to facilitate testing -


here requirements unit testing:

  1. i unit test production classes
  2. i separate test code , production code apart such can release production code only

this seems reasonable requirements. however, problem arises when need use methods such assertequals on objects these requires equals method overridden. equals method have implemented in production classes but used testing. becomes worse when coding practices dictates if equals overridden, should hashcode implemented resulting in more unused production code clutters production classes.

here simple example user model (intellij autoimplemented equals , hashcode)

public class user {     public long id;     public long companyid;     public string name;     public string email;     public long version;      @override     public boolean equals(object o)     {         if(this == o) return true;         if(o == null || getclass() != o.getclass()) return false;         user user = (user) o;         if(companyid != user.companyid) return false;         if(id != user.id) return false;         if(version != user.version) return false;         if(!email.equals(user.email)) return false;         if(!name.equals(user.name)) return false;         return true;     }      @override     public int hashcode()     {         int result = (int) (id ^ (id >>> 32));         result = 31 * result + (int) (companyid ^ (companyid >>> 32));         result = 31 * result + name.hashcode();         result = 31 * result + email.hashcode();         result = 31 * result + (int) (version ^ (version >>> 32));         return result;     } } 

as can seen, equals , hashcode takes lot of space , clutters class.

one solution problem create class, usertester, have assertuserequals method used instead of eg. junit's assertequals.

another solution create usercomparator. however, not seem junit have assertequals takes comparator.

what best practices on point?

uniutils has perfect reflection equals method can use unit testing. way production code remains clear test stuff.

public class user {       private long id;      private string first;      private string last;       public user(long id, string first, string last) {          this.id = id;          this.first = first;          this.last = last;      }  } 

later in test:

user user1 = new user(1, "john", "doe");  user user2 = new user(1, "john", "doe");  assertreflectionequals(user1, user2); 

if you're using mockito has it's own means same thing:

mockito.verify(userdeleter).delete(mockito.refeq(user)); 

Comments

Popular posts from this blog

ios - RestKit 0.20 — CoreData: error: Failed to call designated initializer on NSManagedObject class (again) -

laravel - PDOException in Connector.php line 55: SQLSTATE[HY000] [1045] Access denied for user 'root'@'localhost' (using password: YES) -

java - Digest auth with Spring Security using javaconfig -