[英]Unpredictable behaviour of scala triple quoted string
I'm using junit in scala to compare string output from my scala code. 我在scala中使用junit来比较我的scala代码中的字符串输出。 Something like :
就像是 :
val expected = """<Destination id="0" type="EMAIL">
<Address>
me@test.com
</Address>
<TimeZone>
US/Eastern
</TimeZone>
<Message>
</Message>
</Destination>
"""
val actual = getTextToLog()
info(" actual = " + actual)
assert(expected == actual)
The issue is that for some strings, assertions like : 问题是对于某些字符串,断言如:
assert(expected == actual)
work and for some they strings they dont. 工作和一些他们串起来他们不。 Even when I copy actual (logged to Eclipse console) from Eclipse console and paste it into expected just to be sure , the assertion still fails.
即使我从Eclipse控制台复制实际(登录到Eclipse控制台)并将其粘贴到预期中以确保,断言仍然失败。
What am I missing? 我错过了什么?
OK, since this turns out to be a whitespace issues, you should sanitise the two strings before comparing them. 好的,因为这是一个空白问题,你应该在比较它们之前清理这两个字符串。 Look at the RichString methods like
.lines
, for example, which might let you create a line-ending or whitespace-agnostic comparison method. 例如,查看像
.lines
这样的RichString方法,它们可以让您创建一个行结束或与空白无关的比较方法。
Here is one naive way of doing this with implicit conversions: 这是使用隐式转换执行此操作的一种天真方式:
import scala.language.implicitConversions
object WhiteSpace {
implicit def strToWhiteSpace(s: String) = new WhiteSpace(s)
}
class WhiteSpace(val s: String) {
def `~==` (other: String) = s.lines.toList == other.lines.toList
}
which allows 这使得
import WhiteSpace._
assert(expected ~== actual)
Or you could extend the appropriate jutils class to add an agnostic version of assertEquals
. 或者您可以扩展相应的jutils类以添加断言版本的
assertEquals
。
Note that this comparison deconstructs both strings in the same way. 请注意,此比较以相同方式解构两个字符串。 This is much safer than sending one of them on a round-trip conversion.
这比在往返转换中发送其中一个更安全。
Whitespace/crlf issues are so common that there's no point fighting it by trying to stop the mismatches; 空白/ crlf问题是如此常见,以至于试图阻止不匹配是没有意义的。 just do agnostic comparisons.
只做不可知的比较。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.