I am trying to do a simple example with JUnit parameters with finding the minimum of a list. I am also trying to make this work with different object types but having trouble doing so. Here is what I have so far:
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));
}
}
First I am unable to add to the list with type T, but I am unsure how to format the input values so that they can handle any object type. Also the test is complaining that the call to min is not the proper input type.
The min method is of the format:
public static <T extends Comparable<? super T>> T min (List<? extends T> list)
Not sure how to handle everything with unknown types.
This is how you can get your test running. I did three changes
MinTest<T>
is now MinTest<T extends Comparable<? super T>>
so that T
matches the type of the min
methodList<T>
instead of List<? extends T>
list = new ArrayList<T>();
) so that the constructor can add elements to the list.This is how your test class will look like.
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>> {
public List<T> list = new ArrayList<T>();
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));
}
}
By the way calcValues
can return an Object[][]
array directly:
@Parameters
public static Object [][] calcValues()
{
return new Object [][] {
// Last value indicates expected value
{1, 3, 1},
{"a", "b", "a"}
};
}