How can I create a test class where I can inject the class to be used for testing?
For example, let's say I have a interface ISort
and some concrete classes InsertionSort
, MergeSort
, etc which implement ISort
. Since the test cases for all ISort
are the same, How can I write a common test class and inject the concrete class to be tested?
This is what I have tried so far
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.*;
public class SortTest {
private ISort sortingAlgorithm;
public SortTest(ISort sortingAlgorithm) {
this.sortingAlgorithm = sortingAlgorithm;
}
@Test
public void test1() {
int[] data = new int[] {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
int[] expected = new int[] {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
assertArrayEquals(expected, sortingAlgorithm.sort(data));
}
@Test
public void test2() {
int[] data = new int[] {10, 9, 8, 7, 6, 5, 4, 3, 2, 1};
int[] expected = new int[] {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
assertArrayEquals(expected, sortingAlgorithm.sort(data));
}
// .. more tests
}
How to run tests from SortTest
using InsertionSortTest
class ?
class InsertionSortTest {
// ??
}