我正在使用测试用例 (JUnit5) 将通过一系列方法生成的 2D 数组与我制作的应该相同的 2D 数组进行比较。
@Test
void testReadCorpus() {
UserInterface UI = new UserInterface();
Translator translator = new Translator();
//For English to French translation
translator.setCorpus("English-French.txt");
translator.readCorpus();
translator.printCorpus();
String[][] corpusA = translator.getCorpus();
String[][] corpusB = {
{"the","le"},
{"the","la"},
{"jellyfish","meduse"},
{"boy","garcon"},
{"dances","danse"},
{"with","avec"},
{"lazy","paresseux"},
{"s melly","puante"},
{"dog","chien"},
{"family","famille"},
{"house","maison"},
{"brother","frere"},
{"sister","soeur"},
{"food","aliments"},
{"flower","fleur"},
{"in","dans"},
};
assertEquals(corpusA, corpusB);
printCorpus 方法打印出 2D 数组 (corpusA),每行通过换行分隔,每列用逗号分隔。输出如下:
the,le
the,la
jellyfish,meduse
boy,garcon
dances,danse
with,avec
lazy,paresseux
smelly,puante
dog,chien
family,famille
house,maison
brother,free
sister,soeur
food,aliments
flower,fleur
in,dans
据我所知,这两个数组是相同的,但在使用assertEqual运行测试用例时出现失败。有什么解决办法或想法吗?
更多背景: 我正在从事的项目是一个直译器。它逐字翻译句子。语料库是一个文件,其中包含一种语言的单词及其另一种语言的翻译,以逗号分隔。几乎就是您在上面看到的输出。我只是使用了 readCorpus() 方法来读取文本文件并将其内容存储在 2D 数组中。
您应该使用
assertArrayEquals
而不是 assertEquals
来断言深度数组相等。
@Test
void testReadCorpus() {
UserInterface UI = new UserInterface();
Translator translator = new Translator();
//For English to French translation
translator.setCorpus("English-French.txt");
translator.readCorpus();
translator.printCorpus();
String[][] corpusA = translator.getCorpus();
String[][] corpusB = {
{"the","le"},
{"the","la"},
{"jellyfish","meduse"},
{"boy","garcon"},
{"dances","danse"},
{"with","avec"},
{"lazy","paresseux"},
{"s melly","puante"},
{"dog","chien"},
{"family","famille"},
{"house","maison"},
{"brother","frere"},
{"sister","soeur"},
{"food","aliments"},
{"flower","fleur"},
{"in","dans"},
};
assertArrayEquals(corpusA, corpusB);
}
深层平等语义由
java.util.Arrays#deepEquals
合约规定:
如果两个数组引用都为 null,或者它们引用的数组包含相同数量的元素,并且两个数组中所有对应的元素对都深度相等,则认为两个数组引用深度相等。
我应该使用这种方法来比较数组
assertTrue(Arrays.deepEquals(corpusA, corpusB));
谢谢@tmarwern 的帮助
AssertJ 现在提供 Assertions.isDeepEquals,它可以提供更好的输出(请参阅 https://stackoverflow.com/a/66935173/411282)