我正在自学CS61B - UCB,我是使用IntelliJ和Junit4.12的初学者。我发现my org.junit.Assert.assertArrayEquals()没有结果

在视频中有这样的节目

在跑步窗口。
这里是TestSort.java的代码
import static org.junit.Assert.*;
import org.junit.Test;
/** Tests the the Sort class. */
public class TestSort {
/** Test the Sort.sort method. */
@Test
public void testSort() {
String[] input = {"i", "have", "an", "egg"};
String[] expected = {"an", "egg", "have", "i"};
Sort.sort(input);
if (input != expected)
{
System.out.println("something wrong!");
}
org.junit.Assert.assertArrayEquals(expected, input);
}
@Test
public void testFindSmallest() {
String[] input = {"i", "have", "an", "egg"};
int expected = 2;
int actual = Sort.findSmallest(input, 0);
assertEquals(expected, actual);
String[] input2 = {"there", "are", "many", "pigs"};
int expected2 = 2;
int actual2 = Sort.findSmallest(input2, 2);
assertEquals(expected2, actual2);
}
@Test
public void testSwap() {
String[] input = {"i", "have", "an", "egg"};
int a = 0;
int b = 2;
String[] expected = {"an", "have", "i", "egg"};
Sort.swap(input, a, b);
assertArrayEquals(expected, input);
}
}这里是Sort.java的代码
public class Sort {
public static void sort(String[] x) {
sort(x, 0);
}
private static void sort(String[] x, int start) {
if (start == x.length) {
return;
}
int smallestIndex = findSmallest(x, start);
swap(x, start, smallestIndex);
sort(x, start + 1);
}
public static void swap(String[] x, int a, int b) {
String temp = x[a];
x[a] = x[b];
x[b] = temp;
}
public static int findSmallest(String[] x, int start) {
int smallestIndex = start;
for (int i = start; i < x.length; i += 1) {
int cmp = x[i].compareTo(x[smallestIndex]);
if (cmp < 0) {
smallestIndex = i;
}
}
return smallestIndex;
}
}我认为Junit的功能是得到绿色部分,它显示了我的代码是如何工作的,并得到了我的两个字符串是否相等的结果。
关于IntelliJ的另一个问题是,我运行它和使用终端编译和操作它之间是否有什么区别?因为当我使用终端时,它会显示这样的东西
我在谷歌上搜索了很多这方面的内容,它总是说我没有把Junit.jar应用到类路径中。我检查过了,我添加了库.在这里输入图像描述
fyi,你可以在这里找到图书馆在这里输入链接描述
我调试了testSort函数,它适用于输入部分和排序函数部分。虽然它给了我在这里输入图像描述的提示,我选择了下载,但它显示源代码没有找到在这里输入图像描述,当我从exist文件在这里输入图像描述中选择源代码时,它使attaching....How保持不变--我能解决这个问题吗?
发布于 2018-12-28 04:39:37
您的代码可能没有像您预期的那样运行,但它的运行与一个更有经验的Java所期望的完全一样。让我解释一下..。
您已经发现了=运算符(或者更准确地说,是!=)的行为,这些操作常常会让经验较少的!=工程师感到意外。=运算符不知道如何处理数组,因此返回到比较引用。在您的例子中,它是比较input和expected,看看它们是否引用了完全相同的对象。在您的代码中,input和expected都声明为新数组,因此它们是不同的、单独的对象;它们不引用相同的对象。
至于assertArrayEquals,它可能根本不使用=操作符。虽然我还没有查看该方法的源代码,但我冒昧地猜测它首先检查引用相等性(它们都引用同一个对象,然后检查它们是否都是数组,然后检查expected的每个元素是否也在input中。
数组可以增加等式的混淆,因为平等有很多定义。平等可以定义为..。
我有一个建议可能会帮助您更好地理解这个问题(以及您将来可能面临的更多问题),就是看看这个方法的源代码,在这个例子中,assertArrayEquals是不起作用的。IntelliJ允许您导航到源代码,或者如果源代码不可用,请查看反编译的字节代码。在Mac上只要命令-点击这个方法。在Windows中可能是Control-click?(对不起,IntelliJ有这么多不同的快捷方式集,我不能说得更具体了。)
关于这个话题的进一步信息..。在Java中,==与equals()之间有什么区别? https://javabeginnerstutorial.com/core-java-tutorial/java-equals-method-vs-operator/
https://stackoverflow.com/questions/53953249
复制相似问题