我为我的程序编写测试时遇到了一些问题。我有一个SortingAlgorithm接口,还有一些像BubbleSort,InsertionSort,QuickSort ......的实现......
我不想为每个SortingAlgorithms实现创建一个TestCase。我想将每个算法类注入一个TestCase,然后分别为每个算法运行TestCase。
怎么做?
我的代码:
public class SortingAlorithmTest {
SortingAlgorithm sortingAlgorithm;
final int amount = 50000;
final int delayTime = 0;
int[] numbers;
public SortingAlorithmTest(SortingAlgorithm sortingAlgorithm){
this.sortingAlgorithm = sortingAlgorithm;
}
@Before
public void setUp() throws Exception {
Random random = new Random();
numbers = new int[amount];
for (int i = 0; i < amount; i++){
numbers[i] = random.nextInt(Preferences.numberScope);
}
AlgorithmDelayer.setDelayTime(delayTime);
}
@Test(expected = NullPointerException.class)
public void passingNullValueTest(){
sortingAlgorithm.sort(null);
}
@Test(timeout = 1000)
public void sortingSpeedTimeTest() {
sortingAlgorithm.sort(numbers);
}
@Test
public void correctSortingTest(){
sortingAlgorithm.sort(numbers);
for (int i = 0; i < amount - 1; i++){
assertTrue(numbers[i] <= numbers[i+1]);
}
}
}
答案 0 :(得分:3)
您可以使用Parameterized测试:
@RunWith(Parameterized.class)
class MyTestClass {
private final SortingAlgorithm algo;
public MyTestClass(SortingAlgorithm algo) {
this.algo = algo;
}
@Parameters
public static List<Object[]> getParameters() {
List<Object[]> params = new ArrayList<>();
// Build your list of parameters somehow.
params.add(new Object[] { new BubbleSort() });
params.add(new Object[] { new QuickSort() });
// ...
return params;
}
@Test
public void test() {
// Exercise your algorithm somehow.
}
}