Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Binary file removed .gradle/6.3/executionHistory/executionHistory.lock
Binary file not shown.
Binary file removed .gradle/6.3/fileChanges/last-build.bin
Binary file not shown.
Binary file removed .gradle/6.3/fileHashes/fileHashes.lock
Binary file not shown.
Empty file removed .gradle/6.3/gc.properties
Empty file.
Binary file removed .gradle/6.5/executionHistory/executionHistory.bin
Binary file not shown.
Binary file removed .gradle/6.5/executionHistory/executionHistory.lock
Binary file not shown.
Binary file removed .gradle/6.5/fileChanges/last-build.bin
Binary file not shown.
Binary file removed .gradle/6.5/fileHashes/fileHashes.bin
Binary file not shown.
Binary file removed .gradle/6.5/fileHashes/fileHashes.lock
Binary file not shown.
Empty file removed .gradle/6.5/gc.properties
Empty file.
Binary file removed .gradle/buildOutputCleanup/buildOutputCleanup.lock
Binary file not shown.
2 changes: 0 additions & 2 deletions .gradle/buildOutputCleanup/cache.properties

This file was deleted.

Binary file removed .gradle/checksums/checksums.lock
Binary file not shown.
Empty file removed .gradle/vcs-1/gc.properties
Empty file.
3 changes: 0 additions & 3 deletions .idea/.gitignore

This file was deleted.

10 changes: 0 additions & 10 deletions .idea/compiler.xml

This file was deleted.

18 changes: 0 additions & 18 deletions .idea/gradle.xml

This file was deleted.

20 changes: 0 additions & 20 deletions .idea/jarRepositories.xml

This file was deleted.

7 changes: 0 additions & 7 deletions .idea/misc.xml

This file was deleted.

6 changes: 0 additions & 6 deletions .idea/vcs.xml

This file was deleted.

23 changes: 11 additions & 12 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,15 +1,14 @@
# Примеры для курса "Разработчик Java" в OTUS
Написать свой тестовый фреймворк.

Группа 2020-09
Поддержать свои аннотации @Test, @Before, @After.

### Преподаватели
Сергей Петрелевич<br>
Стрекалов Павел<br>
Александр Оруджев<br>
Вячеслав Лапин<br>
Виталий Куценко<br>
Дмитрий Коган
Запускать вызовом статического метода с именем класса с тестами.

Студент:
Kashapov Renat (Кашапов Ренат)<br>
renat.kashapov@gmail.com
Т.е. надо сделать:

создать три аннотации - @Test, @Before, @After.
Создать класс-тест, в котором будут методы, отмеченные аннотациями.
Создать "запускалку теста". На вход она должна получать имя класса с тестами, в котором следует найти и запустить методы отмеченные аннотациями и пункта 1.
Алгоритм запуска должен быть следующий:: метод(ы) Before текущий метод Test метод(ы) After для каждой такой "тройки" надо создать СВОЙ объект класса-теста.
Исключение в одном тесте не должно прерывать весь процесс тестирования.
На основании возникших во время тестирования исключений вывести статистику выполнения тестов (сколько прошло успешно, сколько упало, сколько было всего)
9 changes: 9 additions & 0 deletions hw03-testFW/build.gradle
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
plugins {
id 'java'
id 'application'
}

group 'ru.otus'
version '1.0-SNAPSHOT'

mainClassName = 'ru.otus.TestFW'
11 changes: 11 additions & 0 deletions hw03-testFW/src/main/java/ru/otus/After.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
package ru.otus;

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface After {
}
11 changes: 11 additions & 0 deletions hw03-testFW/src/main/java/ru/otus/Before.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
package ru.otus;

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface Before {
}
11 changes: 11 additions & 0 deletions hw03-testFW/src/main/java/ru/otus/Test.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
package ru.otus;

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface Test {
}
62 changes: 62 additions & 0 deletions hw03-testFW/src/main/java/ru/otus/TestFW.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,62 @@
package ru.otus;

import java.lang.annotation.Annotation;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.*;

public class TestFW {
private static short failedTest;
public static void main(String ... args){
System.out.println("Hello, Test Framework");
testStarter(TestedClass.class);
}
static void testStarter(Class<?> clazz) {
Method [] methods = clazz.getDeclaredMethods();
Map<Class<? extends Annotation>, Set<Method>> annotationSetMethod = new HashMap<>();
annotationSetMethod.put(Before.class, new HashSet<>());
annotationSetMethod.put(Test.class, new HashSet<>());
annotationSetMethod.put(After.class, new HashSet<>());
for(Method method:methods){
for(Annotation annotation:method.getDeclaredAnnotations()){
Set<Method> methodSet = annotationSetMethod.get(annotation.annotationType());
if(methodSet!=null){
methodSet.add(method);
}
}
}
annotationSetMethod.get(Test.class).forEach(methodTest -> {
Object testedObject;
try {
testedObject = clazz.getConstructor().newInstance();
if (testedObject == null) {
throw new NullPointerException();
} else {
try {
methodsExecution(annotationSetMethod.get(Before.class), testedObject);
methodTest.invoke(testedObject);
methodsExecution(annotationSetMethod.get(After.class), testedObject);
} catch (Exception e) {
failedTest++;
}
}
} catch (Exception 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.

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

}

});
System.out.println("Failed tests: " + failedTest);
System.out.println("Passed tests: " + (methods.length-failedTest));
}

private static void methodsExecution(Set<Method> methodSet, Object testedObject){
methodSet.forEach(method -> {
try {
method.invoke(testedObject);
}
catch (IllegalAccessException | InvocationTargetException e){
e.printStackTrace();
}
});
}
}
31 changes: 31 additions & 0 deletions hw03-testFW/src/main/java/ru/otus/TestedClass.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
package ru.otus;

public class TestedClass {

public TestedClass(){}

@After
public void methodAfter1(){System.out.println("I'm methodAfter1 (this.hashCode(): " + hashCode() + ")");}

@After
public void methodAfter2(){System.out.println("I'm methodAfter2 (this.hashCode(): " + hashCode() + ")");}

@Before
public void methodBefore1(){
System.out.println("I'm methodBefore1 (this.hashCode(): " + hashCode() + ")");
}

@Before
public void methodBefore2(){
System.out.println("I'm methodBefore2 (this.hashCode(): " + hashCode() + ")");
}

@Test
public void methodTest1(){
System.out.println("I'm methodTest1 (this.hashCode(): " + hashCode() + ")");
throw new ArithmeticException();
}

@Test
public void methodTest2() {System.out.println("I'm methodTest2 (this.hachCode(): " + hashCode() + ")");}
}
2 changes: 1 addition & 1 deletion settings.gradle
Original file line number Diff line number Diff line change
@@ -1,2 +1,2 @@
rootProject.name = 'otus_hw'

include 'hw03-testFW'
5 changes: 0 additions & 5 deletions src/main/java/A.java

This file was deleted.