简体   繁体   English

为hashcode,equals和toString方法生成单元测试

[英]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. toString()不应该有任何“契约”要尊重,所以单元测试它会很奇怪而且没用。

You can take a look at this project regarding equals() . 你可以看看有关equals()这个项目

There is also a JUnit Addon EqualsHashCodeTestCase 还有一个JUnit Addon EqualsHashCodeTestCase


On the same topic: 在同一主题上:

EqualsVerifier is a great library. EqualsVerifier是一个很棒的库。 I'm often combining it with Reflections library to automatically scan for certain classes and test the contract for all of them at once: 我经常将它与Reflections库结合起来,自动扫描某些类并立即测试所有类的合同:

 @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. 我建议使用EqualsVerifier来测试哈希码和equals方法。

I would recommend ToStringVerifier for testing toString method 我建议使用ToStringVerifier来测试toString方法

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. 您可以使用Apache EqualsBuilder和HashCodeBuilder来实现equals和hashCode,从而最大限度地降低未正确执行的风险。

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 测试equals很简单,创建两个实例值相同的实例(你希望它们相等)并在一个实例上调用equals传递另一个作为参数,你应该期望它返回true:D

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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