我正在使用一个将字符串转换为等效Unicode字符的库。问题是,在编写单元测试以将Unicode值与自身进行比较时,即使两个值相等,测试也会失败。
这是我的代码:
@Test
public void whenTranslate_thenCorrect() {
UnicodeEscaper ue = UnicodeEscaper.above(0);
String result = ue.translate("ABCD");
Assert.assertEquals("\u0041\u0042\u0043\u0044", result);
}
即使result
对象的值与预期值保持相同,测试也会失败。这是我得到的痕迹:
org.junit.ComparisonFailure: expected:<[ABCD]> but was:<[\u0041\u0042\u0043\u0044]>
at org.junit.Assert.assertEquals(Assert.java:115)
at org.junit.Assert.assertEquals(Assert.java:144)
at com.play.text.UnicodeEscaperTest.whenTranslate_thenCorrect(UnicodeEscaperTest.java:14)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:497)
at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:50)
at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:47)
at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)
at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:325)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:78)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:57)
at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:86)
at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:459)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:675)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:382)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:192)
为什么在翻译之前期望相同的值?
答案 0 :(得分:0)
在您的源文件中,您已编写
SELECT balance
FROM superchart
WHERE balance not regexp '^[-]?[0-9]*[.]?[0.9]*$';
Assert.assertEquals("\u0041\u0042\u0043\u0044", result);
之类的代码段是Unicode escapes。在编译器查看代码之前,它们被识别并转换为相应的UTF-16代码单元。换句话说,上面的那行代码首先实际上被翻译为
\u0041
作为编译的一部分。这意味着在运行时,您将Assert.assertEquals("ABCD", result);
的值与字符串值result
进行比较。但是,您的"ABCD"
变量实际上是引用值为result
的{{1}},即字面意思,即。在运行时构造,而不是源代码中的Unicode转义。
如果您希望在源代码中将该值作为String
字面值,则必须转义"\u0041\u0042\u0043\u0044"
,以便编译器不会将后面的内容解释为Unicode转义。
例如
String