似乎某处有一个非常愚蠢的错误,因为以下 hello-world 程序对我不起作用。
import com.google.common.io.BaseEncoding;
import junit.framework.Test;
import junit.framework.TestCase;
import junit.framework.TestSuite;
String hello = "hello";
junit.framework.Assert.assertEquals(
hello.getBytes(),
BaseEncoding.base64().decode(
BaseEncoding.base64().encode(hello.getBytes())
)
);
Run Code Online (Sandbox Code Playgroud)
我什至试过 hello.getBytes("ISO-8859-1")
我错过了什么?
数组(令人困惑)不会覆盖Object.equals()(同样它们不会覆盖.toString(),这就是为什么您在打印数组时会看到那些无用的\[Lsome.Type;@28a418fc字符串),这意味着调用.equals()两个等效数组不会给您预期的结果:
System.out.println(new int[]{}.equals(new int[]{}));
Run Code Online (Sandbox Code Playgroud)
这打印false. 啊。有关更多信息,请参阅Effective Java Item 25:Prefer lists to arrays。
相反,您应该使用类中的静态辅助函数Arrays对数组执行此类操作。例如这打印true:
System.out.println(Arrays.equals(new int[]{}, new int[]{}));
Run Code Online (Sandbox Code Playgroud)
所以尝试Arrays.equals()或 JUnit 的Assert.assertArrayEquals()而不是Assert.assertEquals():
junit.framework.Assert.assertArrayEquals(
hello.getBytes(),
BaseEncoding.base64().decode(BaseEncoding.base64().encode(hello.getBytes())
)
);
Run Code Online (Sandbox Code Playgroud)
这应该按预期运行。
| 归档时间: |
|
| 查看次数: |
4920 次 |
| 最近记录: |