类型为 T 的 Java 参数化 JUnit

我试图用 JUnit 参数做一个简单的例子,找到列表的最小值。我也在尝试使用不同的对象类型进行这项工作,但这样做时遇到了麻烦。这是我到目前为止所拥有的:


import static org.junit.Assert.*;

import java.util.*;

import org.junit.*;

import org.junit.runner.RunWith;

import org.junit.runners.Parameterized;

import org.junit.runners.Parameterized.Parameters;


@RunWith (Parameterized.class)

public class MinTest<T> {


    public List<? extends T> list;

    public T min;


    public MinTest(T a, T b, T c) {

        this.list.add(a);

        this.list.add(b);

        this.min = c;

    }


    @Parameters

      public static Collection<Object[]> calcValues()

      {

          return Arrays.asList (new Object [][] {

             // Last value indicates expected value

             {1, 3, 1},

             {"a", "b", "a"}

             }); 

      }


    @Test

    public void minTest() {


        assertTrue("Single element list", min == Min.min(list));

    }


}

首先,我无法将类型 T 添加到列表中,但我不确定如何设置输入值的格式,以便它们可以处理任何对象类型。测试还抱怨对 min 的调用不是正确的输入类型。


min 方法的格式为:


public static <T extends Comparable<? super T>> T min (List<? extends T> list)

不确定如何处理未知类型的所有内容。


吃鸡游戏
浏览 157回答 1
1回答

BIG阳

这就是您可以运行测试的方法。我做了三个改变MinTest<T>现在是MinTest<T extends Comparable<? super T>>这样T匹配min方法的类型修复了列表的类型:List<T>而不是List<? extends T>初始化列表 (&nbsp;list = new ArrayList<T>();) 以便构造函数可以向列表添加元素。这就是您的测试类的样子。import static org.junit.Assert.*;import java.util.*;import org.junit.*;import org.junit.runner.RunWith;import org.junit.runners.Parameterized;import org.junit.runners.Parameterized.Parameters;@RunWith (Parameterized.class)public class MinTest<T extends Comparable<? super T>> {&nbsp; &nbsp; public List<T> list = new ArrayList<T>();&nbsp; &nbsp; public T min;&nbsp; &nbsp; public MinTest(T a, T b, T c) {&nbsp; &nbsp; &nbsp; &nbsp; this.list.add(a);&nbsp; &nbsp; &nbsp; &nbsp; this.list.add(b);&nbsp; &nbsp; &nbsp; &nbsp; this.min = c;&nbsp; &nbsp; }&nbsp; &nbsp; @Parameters&nbsp; &nbsp; public static Collection<Object[]> calcValues()&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; return Arrays.asList (new Object [][] {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; // Last value indicates expected value&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; {1, 3, 1},&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; {"a", "b", "a"}&nbsp; &nbsp; &nbsp; &nbsp; });&nbsp; &nbsp; }&nbsp; &nbsp; @Test&nbsp; &nbsp; public void minTest() {&nbsp; &nbsp; &nbsp; &nbsp; assertTrue("Single element list", min == Min.min(list));&nbsp; &nbsp; }}顺便calcValues可以Object[][]直接返回一个数组:@Parameterspublic static Object [][] calcValues(){&nbsp; &nbsp; return new Object [][] {&nbsp; &nbsp; &nbsp; &nbsp; // Last value indicates expected value&nbsp; &nbsp; &nbsp; &nbsp; {1, 3, 1},&nbsp; &nbsp; &nbsp; &nbsp; {"a", "b", "a"}&nbsp; &nbsp; };}
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java