简体   繁体   中英

Generate unit tests for hashcode,equals and toString methods

是否有任何工具/库可以自动生成我的哈希码的测试,并等于查看这些方法中涉及的实例变量的方法?

Guava使用测试构建器来测试equalshashCode

toString() should not have any "contract" to respect, so unit testing it would be weird and not useful.

You can take a look at this project regarding equals() .

There is also a JUnit Addon EqualsHashCodeTestCase


On the same topic:

EqualsVerifier is a great library. I'm often combining it with Reflections library to automatically scan for certain classes and test the contract for all of them at once:

 @Test
  public void validateEqualsHashCodeToString() {
    final Reflections dtoClassesReflections = new Reflections(new ConfigurationBuilder()
      .setUrls(ClasspathHelper.forPackage("my.base.package"))
      .filterInputsBy(new FilterBuilder()
        .include(".*Dto.*") // include all Dto classes
        .exclude(".*Test.*")) // exclude classes from tests which will be scanned as well
      .setScanners(new SubTypesScanner(false)));

    final Set<Class<?>> allDtoClasses = dtoClassesReflections.getSubTypesOf(Object.class);

    allDtoClasses.forEach(dtoClass -> {
      logger.info("equals/hashCode tester testing: " + dtoClass);
      EqualsVerifier.forClass(dtoClass).verify();

      try {
        dtoClass.getDeclaredMethod("toString");
      } catch (NoSuchMethodException e) {
        fail(dtoClass + " does not override toString() method");
      }
    });
  }

I would recommend EqualsVerifier for testing hash code and equals method.

I would recommend ToStringVerifier for testing toString method

Here is an example:

@Test
public void testToString()
{
    ToStringVerifier.forClass(User.class).verify();
}

You can use the Apache EqualsBuilder and HashCodeBuilder to implement equals and hashCode and thus minimize the risk of not doing it properly.

Testing equals is simple, create two instances with instance values the same (by which you will expect them to be equal) and invoke equals on an instance passing the other as a parameter, and you should expect it to return true :D

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM