在ScalaTest中,我进行了以下检查:
"abc".r shouldBe "abc".r
但这并不相等。我不明白。
abc was not equal to abc
ScalaTestFailureLocation: com.ing.cybrct.flink.clickstream.ConfigsTest$$anonfun$6 at (ConfigsTest.scala:97)
Expected :abc
Actual :abc
答案 0 :(得分:9)
虽然它是possible to decide whether two regular expressions accept the same language,但似乎相当复杂,对于日常的正则表达式使用来说,并不是所有功能都非常有用。因此,编译后的正则表达式模式上的相等只是引用相等:
public ngOnDestroy()
{
this.HoverListener.remove();
}
答案 1 :(得分:5)
Scalatest 3.0.5中的方法shouldBe
将相等性检查委托给areEqualComparingArraysStructurally
方法:
def shouldBe(right: Any): Assertion = {
if (!areEqualComparingArraysStructurally(leftSideValue, right)) {
val (leftee, rightee) = Suite.getObjectsForFailureMessage(leftSideValue, right)
val localPrettifier = prettifier // Grabbing a local copy so we don't attempt to serialize AnyShouldWrapper (since first param to indicateFailure is a by-name)
indicateFailure(FailureMessages.wasNotEqualTo(localPrettifier, leftee, rightee), None, pos)
}
else indicateSuccess(FailureMessages.wasEqualTo(prettifier, leftSideValue, right))
}
依次简单地将相等性检查(如您所料)委托给==
运算符:
private[scalatest] def areEqualComparingArraysStructurally(left: Any, right: Any): Boolean = {
// Prior to 2.0 this only called .deep if both sides were arrays. Loosened it
// when nearing 2.0.M6 to call .deep if either left or right side is an array.
// TODO: this is the same algo as in scalactic.DefaultEquality. Put that one in
// a singleton and use it in both places.
left match {
case leftArray: Array[_] =>
right match {
case rightArray: Array[_] => leftArray.deep == rightArray.deep
case _ => leftArray.deep == right
}
case _ => {
right match {
case rightArray: Array[_] => left == rightArray.deep
case _ => left == right
}
}
}
}
在Scala中,至少在JVM上,==
简单地调用equals
,如果没有重写,则检查比较的变量是否指向同一对象。 case class
的独特之处在于,编译器会覆盖equals
,以便您比较构造函数参数。
您可以使用以下命令非常轻松地对其进行测试(但可以想象,对您自己单独使用==
也是如此)
package org.example
import org.scalatest.{FlatSpec, Matchers}
final class MyClass(val a: Int)
final case class MyCaseClass(a: Int)
final class TestSpec extends FlatSpec with Matchers {
"equality on case classes" should "succeed" in {
new MyCaseClass(1) shouldBe new MyCaseClass(1)
}
"equality on non-case classes" should "fail" in {
new MyClass(1) shouldNot be(new MyClass(1))
}
"equality between Regex objects" should "fail" in {
"abc".r shouldNot be("abc".r)
}
}
r
方法的作用是实例化一个新的Regex
对象,该对象不是case class
,并且不会覆盖相等性定义,从而产生您看到的结果。
答案 2 :(得分:0)
是的,它们不相等。两个"abc".r
是对两个不同存储位置的不同引用。 应该用于检查 equality
,而不是 identity
。