我是Java& Junit测试。我的问题是,如何使用以下Junit测试代码修复我得到的错误。使用print语句检查时,Java代码返回所需的输出。非常感谢任何帮助。
Junit测试代码
import static org.junit.Assert.*;
import java.util.Arrays;
import org.junit.Test;
public class RemoveDuplicateTest {
@Test
public void test() {
RemoveDuplicatesStringArray rd = new RemoveDuplicatesStringArray();
String[] strArray = {"ellen","talk","show","ellen","talk","show","ellen","talk"};
rd.removeDups(strArray);
assertEquals(Arrays.asList("show","ellen","talk"),strArray.toString());
}
}
Java代码:
import java.util.*;
public class RemoveDuplicatesStringArray {
public List<String> removeDups(String[] str){
List<String> strList = new ArrayList<>();
int count = 0;
for(int i = 0; i < str.length; i++){
for(int j = i+1; j < str.length; j++){
if(str[i].equals(str[j])){
count += 1;
}
}
if(count < 1){
strList.add(str[i]);
}
count = 0;
}
for(int k = 0; k < strList.size(); ){
System.out.println("check "+strList);
System.out.println(strList.getClass());
return(strList);
}
return null;
}
}
答案 0 :(得分:0)
要回答你的问题,你的测试有几个错误:
String[] strArray = {"ellen","talk","show","ellen","talk","show","ellen","talk"};
rd.removeDups(strArray);
removeDups
保持传递的数组不变,您忽略应该只包含唯一元素的列表的结果。
assertEquals(Arrays.asList("show","ellen","talk"),strArray.toString());
在这里,您将列表与String数组的字符串表示形式进行比较。这永远不会被评估为平等。即使你把它改成
assertEquals(Arrays.asList("show","ellen","talk").tostring(), Arrays.asList(strArray).toString());
您仍然将完整数组与所有重复值进行比较,并使用唯一值导致相同结果的值。
我想你想做foll
public void test() {
RemoveDuplicatesStringArray rd = new RemoveDuplicatesStringArray();
String[] strArray = {"ellen","talk","show","ellen","talk","show","ellen","talk"};
List<String> checkList = rd.removeDups(strArray);
assertEquals(Arrays.asList("ellen","talk","show").tostring(),checkList.toString());
}
我更改了包含期望值的列表中值的顺序,因为这些值按照它们第一次出现在源列表中的顺序添加到结果列表中。否则你的支票仍然是否定的。
顺便说一句:removeDups
是表演地狱。正如评论中所提到的,使用HashSet
或类似的类会更好,因为它们是