JUnit - 必须返回数组Collection错误

时间:2014-08-26 10:06:05

标签: junit junit-runner

public class EmployeeDetails {

    private String name;
    private double monthlySalary;
    private int age;

    /**
     * @return the name
     */
    public String getName() {
            return name;
        }
        /**
         * @param name the name to set
         */
    public void setName(String name) {
            this.name = name;
        }
        /**
         * @return the monthlySalary
         */
    public double getMonthlySalary() {
            return monthlySalary;
        }
        /**
         * @param monthlySalary the monthlySalary to set
         */
    public void setMonthlySalary(double monthlySalary) {
            this.monthlySalary = monthlySalary;
        }
        /**
         * @return the age
         */
    public int getAge() {
            return age;
        }
        /**
         * @param age the age to set
         */
    public void setAge(int age) {
        this.age = age;
    }
}

如何将EmployeeDetails.class列表传递给JUnit参数化类。

请帮我编写参数方法

@Parameters
public static Collection employeeList()
{
    List<EmployeeDetails> employees = new ArrayList<EmployeeDetails>;
    return employees;
}

//抛出错误,如“employeeList必须返回数组集合。”

上面的EmployeeDetails类是一个例子。我需要将它用于类似的类,我将发送类对象的列表。

3 个答案:

答案 0 :(得分:2)

您的@Parameters方法必须返回一组对象数组。因此,假设您的测试用例构造函数只需要一个EmployeeDetails对象,请执行以下操作:

@Parameters
public static Collection<Object[]> employeeList() {
    List<EmployeeDetails> employees = new ArrayList<>();
    // fill this list

    Collection<Object[]> result = new ArrayList<>();
    for (EmployeeDetails e : employees) {
        result.add(new Object[] { e });
    }
    return result;
}

答案 1 :(得分:0)

如果您可以使用静态构造函数,那么在您的设置中可能会更加轻松

@Parameterized.Parameters
public static Collection<Object[]> params() {
  return Arrays.asList(new Object[][] {
      { 0, "a" },
      { 1, "b" },
      { 3, "c" },
  });
}

答案 2 :(得分:-2)

Collection是一个泛型类型,你必须指定返回的Collection<E>的类型,其中E是类型,这里必须是EmployeeDetails

您的代码必须如下所示:

public static Collection<EmployeeDetails> employeeList()
{
List<EmployeeDetails> employees = new ArrayList<EmployeeDetails>();
return employees;
}

或只是

public static Collection<?> employeeList()
{
List<EmployeeDetails> employees = new ArrayList<EmployeeDetails>();
return employees;
}