Skip to content

hw03 test fw - #3

Open
1121977 wants to merge 7 commits into
masterfrom
hw03-testFW
Open

hw03 test fw#3
1121977 wants to merge 7 commits into
masterfrom
hw03-testFW

Conversation

@1121977

@1121977 1121977 commented Oct 25, 2020

Copy link
Copy Markdown
Owner

Homework #3. Test framework.

testStarter(TestedClass.class);
}
static void testStarter(Class<?> clazz) {
Method methods[] = clazz.getDeclaredMethods();

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

так не принято объявлять массивы, должно быть:
Method[] methods = clazz.getDeclaredMethods();

Copy link
Copy Markdown
Owner Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Принято, исправлю.

if (annotations.length!=0)
for (Annotation annotation:annotations)
switch (annotation.toString()) {
case ("@ru.otus.After()"):

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

очень плохо аннотации по строке опознавать.
найдите метот, который позволит работать с аннотацией как с классом.

Annotation[] annotations = method.getDeclaredAnnotations();
if (annotations.length!=0)
for (Annotation annotation:annotations)
switch (annotation.toString()) {

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

лучше вместо страшного switch сделать метод типа findAnnotatedMethods, который как входной параметр будет принимать нужную аннотацию.

Copy link
Copy Markdown
Owner Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Страшный switch засадить/спрятать внутрь findAnnotatedMethods? Или, если есть возможность работать с аннотациями как с классами, из них собрать ArrayList?

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

основная идея в том, чтобы совсем отказаться от switch. findAnnotatedMethods надо вызвать нужное кол-во раз для нужных аннотаций

throw new AnnotationTypeMismatchException(method, "Unkown annotaion");
}
}
methodsWithTestAnnotation.forEach(_methodTest -> {

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

_methodTest - так не приниято именовать переменные,
лучше methodTest

Copy link
Copy Markdown
Owner Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Принято, исправлю.

Object testedObject;
try {
testedObject = clazz.getConstructor().newInstance();
if (testedObject == null)

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

всегда используйте {}, даже для одной строки кода.

Copy link
Copy Markdown
Owner Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Принято исправлю.

}
methodsExecution(methodsWithAfterAnnotaion, testedObject);
} catch (InstantiationException| IllegalAccessException | InvocationTargetException | NoSuchMethodException | NullPointerException e) {
e.printStackTrace();

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

если в before или after будет ошибка, то тест отметится как успешный?

Copy link
Copy Markdown
Owner Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Да, именно так и произойдет. Тут я не совсем понимаю целевого назначения тестирования относительно Before и After. Методы, помеченные ими, также являются частью тестов? Исходил из того, что бизнес ценностью являются методы, помеченные Test, ради них всё и затевается.

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

формально тест состоит из трех этапов: подготовка данных - выполнение - завершение.
Я бы считал тест пройденным, если успешно выполнены все три этапа.
Но это не принципиально для ДЗ.

else
methodsExecution(methodsWithBeforeAnnotaion,testedObject);
try {
_methodTest.invoke(testedObject);

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

если .invoke(testedObject); делаете в методе, типа methodsExecution, то лучше придерживаться этого стиля во всей программе.

Copy link
Copy Markdown
Owner Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Принято, исправлю.

List<Method> methodsWithAfterAnnotaion = new ArrayList<>();
List<Method> methodsWithBeforeAnnotaion = new ArrayList<>();
List<Method> methodsWithTestAnnotation = new ArrayList<>();
for(Method method:methods) {

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

под подготовки к запуску лучше в отдельный метод вынести.

Copy link
Copy Markdown
Owner Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Не совсем понятно. findAnnotatedMethods не достаточно будет?

@petrelevich petrelevich Oct 27, 2020

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

findAnnotatedMethods - это просто функционал для поиска нужных методов.

под подготовки к запуску лучше в отдельный метод вынести.

а метод подготовки к запуску тестов - это единица структуры программы.
так мы ясно показываем: вот метод подготовки к тестам, а вот - запуск тестов.
Такая структура облегчает понимание и сопровождение программы.

List<Method> methodsWithTestAnnotation = new ArrayList<>();
for(Method method:methods) {
Annotation[] annotations = method.getDeclaredAnnotations();
if (annotations.length!=0)

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

не забывайте про форматирование кода,
в Idea это alt-ctl-l

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.function.Predicate;

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

удаляйте неиспользуемые импорты.

Copy link
Copy Markdown
Owner Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Принято исправлю.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants