How to test anonymous inner classes

6 views
Skip to first unread message

Tom Wieczorek

unread,
Jan 4, 2019, 3:22:50 AM1/4/19
to equalsverifier
Consider a class like this:

public abstract class Foo<T> {
   
public static <T> Foo<T> of(T value) {
       
Objects.requireNonNull(value);
       
return new Foo<T>() {
           
@Override
           
public String toString() {
               
return String.format("Foo.of(%s)", value);
           
}

           
@Override
           
public boolean equals(Object obj) {
                   
return obj != null && getClass() == obj.getClass() && value.equals(((Foo<?>) obj).get());
           
}

           
@Override
           
public int hashCode() {
               
return Objects.hash(getClass(), value);
           
}

           
@Override
           
public T get() {
               
return value;
           
}
       
};
   
}

   
public abstract T get();
}



I failed to write a working EqualsVerifier test for the instances returned by Foo::of.

The culprit is that the actual value that's held by Foo instances created by of() is a synthetic field, and therefore is skipped by EqualsVerifier. I cannot provide examples for a relaxed equality check, too, since we need to have two equal instances which have at least one non-equal member (which also won't work with the above class structure).

Any ideas?

Thanks,
Tom.
Reply all
Reply to author
Forward
0 new messages