【发布时间】:2019-02-15 04:20:53
【问题描述】:
在使用 Eclipse JUnit 和 gradle 测试运行单元测试时,我得到了不同的结果。有这样的课程:
@Getter @Setter
@EqualsAndHashCode
public class ObjectWithId {
private Long id;
}
以及类似的测试(将案例压缩到一个测试以节省空间):
@Test
public void testObjectWithId() {
ObjectWithId o1 = new ObjectWithId(), o2 = new ObjectWithId();
o1.setId(1L);
o2.setId(1L);
assertEquals(o1.hashCode(), o2.hashCode());
assertEquals(o1, o2);
o2.setId(2L);
assertNotEquals(o1, o2);
assertNotEquals(o1.hashCode(), o2.hashCode());
}
一切都按预期进行。
然后,有一个像这样的类:
@Getter @Setter
@EqualsAndHashCode(onlyExplicitlyIncluded = true)
public class ObjectWithIdAndDate {
@EqualsAndHashCode.Include
private Long id;
private LocalDateTime created;
}
进行如下测试:
@Test
public void testObjectWithIdAndDate() {
ObjectWithIdAndDate o1 = new ObjectWithIdAndDate(), o2 = new ObjectWithIdAndDate();
o1.setId(1L);
o2.setId(1L);
assertEquals(o1.hashCode(), o2.hashCode());
assertEquals(o1, o2);
o2.setId(2L);
assertNotEquals(o1, o2);
assertNotEquals(o1.hashCode(), o2.hashCode());
o2.setId(1L);
o2.setCreated(LocalDateTime.now());
// Eclipse JUnit starts failing here because setting the created.
// Gradle test will pass.
assertEquals(o1.hashCode(), o2.hashCode());
assertEquals(o1, o2);
o1.setCreated(LocalDateTime.now());
assertEquals(o1.hashCode(), o2.hashCode());
assertEquals(o1, o2);
}
使用 Eclipse JUnit 运行时失败,但使用 gradle 测试成功?我从 Eclipse 和命令行运行 gradle 测试,没有区别。所以,似乎不知何故 gradle 更清楚应该如何对待 @EqualsAndHashCode(onlyExplicitlyIncluded = true)...?
我的build.gradle 中有compile 'org.projectlombok:lombok:1.18.2',我的Eclipse 中安装了相同版本的lombok.jar。
gradle 项目和 Eclipse 都使用 JUnit 4.12 版。我在这里错过了什么?
一些进一步的调查:
我用 Maven 构建了其他相同的项目。令我惊讶的是,这个项目的 JUnit 测试也通过了。
这听起来像是 Eclipse gradle 项目方面或其他一些 gradle 项目特定设置有问题吗?
【问题讨论】:
-
你也在用Eclipse的编译器吗?
-
你的测试也是错误的;第二个
setCreated永远不可能等于相同的LocalDateTime。将其隔离到一个变量中并改用它。 -
@Makoto 我猜是这样,我通过“Run as JUnit test”运行它
-
@Makoto
setCreated(..)是为了测试@EqualsAndHashCode(onlyExplicitlyIncluded = true)的功能,所以如果我理解正确的话,它永远不应该被考虑比较。测试结果是否正确。 -
啊——我没注意到。当我看到有人在两个不同的地方使用
LocalDateTime.now()时,这对我来说只是一种瞬间的气味。
标签: java eclipse gradle junit lombok