Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/345.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 通用方法的JUnit测试用例_Java_Generics_Junit - Fatal编程技术网

Java 通用方法的JUnit测试用例

Java 通用方法的JUnit测试用例,java,generics,junit,Java,Generics,Junit,请原谅我提出了一个潜在的多余的问题,但我最近一直在学习泛型,对于如何测试它们有些不知所措 以下是我在集合中查找最小值的方法的代码: public static <T> T min(Collection<T> c, Comparator<T> comp) { if (c == null || comp == null) { throw new IllegalArgumentException("Collection or comparator is

请原谅我提出了一个潜在的多余的问题,但我最近一直在学习泛型,对于如何测试它们有些不知所措

以下是我在集合中查找最小值的方法的代码:

public static <T> T min(Collection<T> c, Comparator<T> comp) {
  if (c == null || comp == null) {
     throw new IllegalArgumentException("Collection or comparator is null.");
  }
  if (c.isEmpty()) {
     throw new NoSuchElementException("Collection is empty.");
  }
  Iterator<T> itr = c.iterator();
  T min = itr.next();
  if (itr.hasNext()) {
     for (T i : c) {
        if (comp.compare(i, min) < 0) {
           min = i;
        }
     }
  }
  return min;
}
publicstatictmin(集合c,比较器comp){
如果(c==null | | comp==null){
抛出新的IllegalArgumentException(“Collection或comparator为null”);
}
if(c.isEmpty()){
抛出新的NoSuchElementException(“集合为空”);
}
迭代器itr=c.Iterator();
T min=itr.next();
if(itr.hasNext()){
对于(ti:c){
如果(组件比较(i,min)<0){
min=i;
}
}
}
返回最小值;
}
这是我为这种方法准备的最小测试用例:

public class SelectorTest{

  @Test
  public void min() {
     Comparator<Integer> intSort = new IntegerSort();
     Integer[] test = {2, 8, 7, 3, 4};
     int expected = 2;
     int actual = Selector.min(test, intSort);
     Assert.assertEquals(expected, actual);
  }

  public static class IntegerSort implements Comparator<Integer> {
     public int compare(Integer o1, Integer o2) {
        return Integer.compare(o1, o2);
     }
  }
公共类选择器测试{
@试验
公共空间(分钟){
Comparator intSort=新整数排序();
整数[]测试={2,8,7,3,4};
int预期为2;
int实际值=选择器.min(测试,intSort);
Assert.assertEquals(预期、实际);
}
公共静态类IntegerSort实现了Comparator{
公共整数比较(整数o1,整数o2){
返回整数。比较(o1,o2);
}
}
}

我从这段代码中收到的编译器错误如下:

required:java.util.Collection<T>,java.util.Comparator<T>
found: java.lang.Integer[],java.util.Comparator<java.lang.Integer>
必需:java.util.Collection,java.util.Comparator
找到:java.lang.Integer[],java.util.Comparator
很明显,我在测试用例中传递的参数不是应该传递的,但我的想法是这样的:我传递一个整数数组,它是一个集合,我给它一个特定的整数比较器,正如min方法所要求的那样

我应该如何修复这个测试用例,以便以这种方式有效地工作,并且不仅处理整数,而且处理min方法能够处理的任何类型的集合

我以前从未成功地编写过通用测试用例,所以我不知道如何才能做到这一点


谢谢大家!

您的问题与泛型无关。当方法需要集合时,不能将数组作为参数传递。数组不实现集合接口。如果您要传递ArrayList的实例,它应该可以正常工作。

您的问题与泛型无关。当方法需要集合时,不能将数组作为参数传递。数组不实现集合接口。如果要传递ArrayList的实例,它应该可以正常工作。

integer array不实现integer array不实现更合理的方法。非常感谢。这会更有意义。非常感谢。