When I am trying to run the following test:
@Test
public void testHash() {
BeanMatchers.registerValueGenerator(Instant::now, Instant.class);
assertThat(ClassForTest.class, hasValidBeanHashCode());
}
for the class:
class ClassForTest {
private Instant instant;
public Instant getInstant() {
return instant;
}
public void setInstant(Instant instant) {
this.instant = instant;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
ClassForTest that = (ClassForTest) o;
return Objects.equals(instant, that.instant);
}
@Override
public int hashCode() {
return Objects.hash(instant);
}
}
where BeanMatchers
class comes from:
<dependency>
<groupId>com.google.code.bean-matchers</groupId>
<artifactId>bean-matchers</artifactId>
<version>0.14</version>
<scope>test</scope>
</dependency>
I am constantly getting the following exception:
BeanMatchers Could not generate two distinct values after 128 attempts of type java.time.Instant
Any ideas why I see this exception and how to fix it? Because, technically, the test is implemented in the right way.
I was facing the same issue, I resolved it like this
@Test
public void testHash() {
BeanMatchers.registerValueGenerator(this::registerInstant, Instant.class);
assertThat(ClassForTest.class, hasValidBeanHashCode());
}
private Instant registerInstant() {
List<Instant> times = Arrays.asList(Instant.now(), Instant.now().minusSeconds(10));
return times.get(new Random().nextInt(times.size()));
}