junit的EqualsWithDelta使用方法

How to use EqualsWithDelta of junit

版本:

<dependency>
  <groupId>org.mockito</groupId>
  <artifactId>mockito-all</artifactId>
  <version>1.9.5</version>
  <scope>test</scope>
</dependency>
<dependency>
  <groupId>org.junit.jupiter</groupId>
  <artifactId>junit-jupiter-api</artifactId>
  <version>5.2.0</version>
  <scope>test</scope>
</dependency>
<dependency>
  <groupId>org.junit.jupiter</groupId>
  <artifactId>junit-jupiter-engine</artifactId>
  <version>5.2.0</version>
  <scope>test</scope>
</dependency>

我正在尝试使用 EqualsWithDelta like below, which is not working, however in similar way Equals 作品,我在实施中是否遗漏了什么:

import org.junit.Assert
import org.mockito.internal.matchers.{Equals, EqualsWithDelta}
val testVarLong = testFuncReturningLong()
val testVarStr = testFuncReturningString()
Assert.assertThat( System.currentTimeMillis(), new EqualsWithDelta(testVarLong, 1000L))      <-- This does not  work
Assert.assertThat( "myTest", new Equals(testVarStr))   <-- This works

以下是我得到的编译时错误:

Error:(82, 52) type mismatch;
 found   : org.mockito.internal.matchers.EqualsWithDelta
 required: org.hamcrest.Matcher[_ >: Any]
Note: Number <: Any (and org.mockito.internal.matchers.EqualsWithDelta <: org.mockito.ArgumentMatcher[Number]), but Java-defined trait Matcher is invariant in type T.
You may wish to investigate a wildcard type such as `_ <: Any`. (SLS 3.2.10)
    Assert.assertThat( System.currentTimeMillis(), new EqualsWithDelta(testVarLong, 1000L))

尝试投射

assertThat( System.currentTimeMillis(), new EqualsWithDelta(testVarLong, 1000L).asInstanceOf[Matcher[_ >: Long]])

或者干脆

assertThat[Long]( System.currentTimeMillis(), new EqualsWithDelta(testVarLong, 1000L).asInstanceOf[Matcher[Long]])

无论如何,由于类型擦除,在运行时 new EqualsWithDelta... 只是一个 Matcher[_],因此此转换是安全的。 您应该遵循 @AlexeyRomanov 的建议。

Scala type bounds and Java generic interop

new EqualsWithDelta(...) 是一个 Matcher[Number]System.currentTimeMillis() 是一个 LongAssert.assertThat 签名是 assertThat(T actual, org.hamcrest.Matcher<T> matcher)。所以 EqualsWithDelta 必须是 Matcher<T> 的子类型,而 Long 必须是 T 的子类型。第一个暗示 T 必须是 Number,但 Long 不是 Number 的子类型。所以 T 这样的类型推断报告不存在。

但是,如果您通过以下两种方式之一明确要求 Number

assertThat[Number](System.currentTimeMillis(), new EqualsWithDelta(testVarLong, 1000L))

assertThat(System.currentTimeMillis(): Number, new EqualsWithDelta(testVarLong, 1000L))

这将触发 implicit conversionLongjava.lang.Long 作为 Number 的子类型。