📜 ⬆️ ⬇️

On the application of reflection in testing and not only

Many people associate reflection with bloated code or with incorrect api.
Under the cut there are several useful examples that show the positive aspects of reflection.


We will train on ducks sorting.

public interface ISort { int[] sort(int[] ints); } public class MergeSort implements ISort { //   } public class QuickSort implements ISort { //   } 

Just imagine the situation that we want to study a lot of sorts, we want them all to work and be tested.

However, we are too lazy to write tests for all algorithms. Therefore, we will test only the ISort interface, and all other classes, as if by themselves, will be tested)
')
 //      public abstract class ISortTest<T extends ISort> { private Class<T> aClass; private T sortAlgorithm; public ISortTest() { //       aClass = Optional.of(getClass()) .map(Class::getGenericSuperclass) .filter(el -> el instanceof ParameterizedType) .map( el -> (ParameterizedType) el) .filter(el -> el.getActualTypeArguments().length > 0) .map(el -> el.getActualTypeArguments()[0]) .filter(el -> el instanceof Class) .map(el -> (Class<T>) el) .orElse(null); } @BeforeEach void init() throws IllegalAccessException, InstantiationException { //     sortAlgorithm = aClass.newInstance(); } @Test void sortTest() { assertNotNull(sortAlgorithm); int n = 10000; int[] ints = new Random().ints().limit(n).toArray(); int[] sortInts = Arrays.stream(ints) .sorted() .toArray(); int[] testSotrInts = sortAlgorithm.sort(ints); assertArrayEquals(sortInts, testSotrInts); } } 

Well, that's it, now you can officially announce the victory of laziness.

Sorting testing will now be reduced to creating such classes

 class MergeSortTest extends ISortTest<MergeSort> { //    } class QuickSortTest extends ISortTest<QuickSort> { //    } 

A similar approach is used, for example, in Spring Data

 public interface TestRepository extends CrudRepository<MyEntity, Long> { } 

As well as in other places that we do not even guess.

Source: https://habr.com/ru/post/352466/


All Articles