Java单元测试参数化数组

时间:2018-03-17 06:40:31

标签: java arrays junit quicksort parameterized

您好我正在为QuickSort算法进行单元测试(即将随机数中的随机数按升序排序)。但是我无法在Collection中声明一组数字。你能帮忙吗。谢谢。 此行还有语法错误

  

this.arrayIn [] = arrayIn;

我是否正确测试

  

assertEquals(arrayOut,QuickSort.sort(arrayIn));

package week8;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;
import org.junit.runners.Parameterized.Parameters;
import static org.junit.Assert.*;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;

@RunWith(Parameterized.class)
public class QuickSortTest {

private int[] arrayIn[];
private int length;
private int[] arrayOut[];

public QuickSortTest(int[] arrayIn, int length, int[] arrayOut) {
    this.arrayIn[]= arrayIn;
    this.length=length;
    this.arrayOut[]=arrayOut;   
}

@Parameters
public static Collection<Object[]> parameters(){
    return Arrays.asList(new Object[][]{
        {{1,4,6,3,5,4},6,{1,3,4,4,5,6}}
    });
}
@Test
public void test_quicksort() {
    assertEquals(arrayOut, QuickSort.sort(arrayIn));
} 
}

2 个答案:

答案 0 :(得分:0)

私有属性arrayIn的声明:

private int[] arrayIn[];

相当于:

private int[][] arrayIn;

因此,在为其分配值时,您应该:

this.arrayIn = ...; // without the brackets []

我不明白你为什么要使用参数化测试。参数化测试对于测试多个输入集非常有用。而且你只有一个输入集:一个数组和一个长度。因此,例如,使用一种测试方法就足够了。并确保使用正确的断言方法:assertEquals(Object, Object)不适用于此处,您应该使用assertArrayEquals(int[], int[])

public class QuickSortTest {

    @Test
    public void test_quicksort() {
        ...
        assertArrayEquals(expectedArr, actualArr);
    }
}

答案 1 :(得分:0)

感谢assertArrayEquals上的提示 - 当我使用assertEquals时,得到了乱码。 谢谢你的宣言!它现在有效! 是的我打算添加更多参数,但由于我的第一种情况仍然出现错误,我只是停下来检查。我修改了我的代码如下。

@Parameters
public static Collection<Object[]> parameters(){
    return Arrays.asList(new Object[][]{
        {new int[] {1,4,1,6,3,5}, 6, new int[] {1,1,3,4,5,6}},
        {new int[] {1,4,1,6,3,5}, 6, new int[] {1,3,1,4,5,6}},
        {new int[] {70000,4,1,6,3,5}, 7, new int[] {1,3,4,5,6,70000}},
    });
}

@Test
public void test_quicksort() {
   new QuickSort().sort(arrayIn);
   assertArrayEquals(arrayOut, arrayIn);

} 
相关问题