hw03 test fw - #3
Conversation
| testStarter(TestedClass.class); | ||
| } | ||
| static void testStarter(Class<?> clazz) { | ||
| Method methods[] = clazz.getDeclaredMethods(); |
There was a problem hiding this comment.
так не принято объявлять массивы, должно быть:
Method[] methods = clazz.getDeclaredMethods();
| if (annotations.length!=0) | ||
| for (Annotation annotation:annotations) | ||
| switch (annotation.toString()) { | ||
| case ("@ru.otus.After()"): |
There was a problem hiding this comment.
очень плохо аннотации по строке опознавать.
найдите метот, который позволит работать с аннотацией как с классом.
| Annotation[] annotations = method.getDeclaredAnnotations(); | ||
| if (annotations.length!=0) | ||
| for (Annotation annotation:annotations) | ||
| switch (annotation.toString()) { |
There was a problem hiding this comment.
лучше вместо страшного switch сделать метод типа findAnnotatedMethods, который как входной параметр будет принимать нужную аннотацию.
There was a problem hiding this comment.
Страшный switch засадить/спрятать внутрь findAnnotatedMethods? Или, если есть возможность работать с аннотациями как с классами, из них собрать ArrayList?
There was a problem hiding this comment.
основная идея в том, чтобы совсем отказаться от switch. findAnnotatedMethods надо вызвать нужное кол-во раз для нужных аннотаций
| throw new AnnotationTypeMismatchException(method, "Unkown annotaion"); | ||
| } | ||
| } | ||
| methodsWithTestAnnotation.forEach(_methodTest -> { |
There was a problem hiding this comment.
_methodTest - так не приниято именовать переменные,
лучше methodTest
| Object testedObject; | ||
| try { | ||
| testedObject = clazz.getConstructor().newInstance(); | ||
| if (testedObject == null) |
There was a problem hiding this comment.
всегда используйте {}, даже для одной строки кода.
| } | ||
| methodsExecution(methodsWithAfterAnnotaion, testedObject); | ||
| } catch (InstantiationException| IllegalAccessException | InvocationTargetException | NoSuchMethodException | NullPointerException e) { | ||
| e.printStackTrace(); |
There was a problem hiding this comment.
если в before или after будет ошибка, то тест отметится как успешный?
There was a problem hiding this comment.
Да, именно так и произойдет. Тут я не совсем понимаю целевого назначения тестирования относительно Before и After. Методы, помеченные ими, также являются частью тестов? Исходил из того, что бизнес ценностью являются методы, помеченные Test, ради них всё и затевается.
There was a problem hiding this comment.
формально тест состоит из трех этапов: подготовка данных - выполнение - завершение.
Я бы считал тест пройденным, если успешно выполнены все три этапа.
Но это не принципиально для ДЗ.
| else | ||
| methodsExecution(methodsWithBeforeAnnotaion,testedObject); | ||
| try { | ||
| _methodTest.invoke(testedObject); |
There was a problem hiding this comment.
если .invoke(testedObject); делаете в методе, типа methodsExecution, то лучше придерживаться этого стиля во всей программе.
| List<Method> methodsWithAfterAnnotaion = new ArrayList<>(); | ||
| List<Method> methodsWithBeforeAnnotaion = new ArrayList<>(); | ||
| List<Method> methodsWithTestAnnotation = new ArrayList<>(); | ||
| for(Method method:methods) { |
There was a problem hiding this comment.
под подготовки к запуску лучше в отдельный метод вынести.
There was a problem hiding this comment.
Не совсем понятно. findAnnotatedMethods не достаточно будет?
There was a problem hiding this comment.
findAnnotatedMethods - это просто функционал для поиска нужных методов.
под подготовки к запуску лучше в отдельный метод вынести.
а метод подготовки к запуску тестов - это единица структуры программы.
так мы ясно показываем: вот метод подготовки к тестам, а вот - запуск тестов.
Такая структура облегчает понимание и сопровождение программы.
| List<Method> methodsWithTestAnnotation = new ArrayList<>(); | ||
| for(Method method:methods) { | ||
| Annotation[] annotations = method.getDeclaredAnnotations(); | ||
| if (annotations.length!=0) |
There was a problem hiding this comment.
не забывайте про форматирование кода,
в Idea это alt-ctl-l
| import java.util.ArrayList; | ||
| import java.util.Arrays; | ||
| import java.util.List; | ||
| import java.util.function.Predicate; |
Homework #3. Test framework.