Создание класса времени выполнения Java с аннотацией @RunWith(SerenityRunner.class) не отражающей

Я работаю над созданием фреймворка для тестирования API с использованием BDD безмятежности. В текущем сценарии бизнес требует вывести все тестовые случаи API из Excel, включая Test-data, утверждения и итерации.

Помня об этом, я только начал внедрять фреймворк, расширив возможности Serenity Rest-Assured и Junit. Во время моего прогресса я не получаю представление о том, как создать класс времени выполнения на основе деталей строки, представленных в нескольких файлах Excel.

Мне удалось создать класс во время выполнения, но проблема заключается в добавлении аннотации на уровне класса (ниже структуры, которую я назвал).

    @RunWith(SerenityRunner.class)
public class DataServicesTest extends CustomSerenityRunner {
}

Я добавил зависимость

Javassist

библиотека для создания класса во время выполнения. Но не удается продолжить добавление "аннотации" для вновь созданного класса или метода.

    @RunWith(SerenityRunner.class)
public class ServicesTest extends SerenityRunner {

    public static Logger logger = LoggerFactory.getLogger(ServicesTest.class);

    public ServicesTest() throws InitializationError {
        super(ServicesTest.class);
        logger.info("Test Execution Started from serviceTest : " + ServicesTest.class);
        runtimeMethodAnnotation();
    }

    @Steps
    UserManagementControllerTestSteps userManagementControllerTestSteps;

    @Test
    public void loadTest() {
        userManagementControllerTestSteps.getAllUsersCall();
    }

    public void runtimeMethodAnnotation() {
        ClassPool classpool = ClassPool.getDefault();
        classpool.importPackage("com.bhge.tests");
        CtClass ctClass = classpool.makeClass("ServiceCallToGetAllUsers");
        try {
            CtMethod runtimeMethod = CtMethod.make(
                    "public void callAllUserEndpoint (java.lang.String endPoint) { net.serenitybdd.rest.SerenityRest.given().accept(\"java.lang.String */*\").baseUri(\"java.lang.String http://54.564.64.44/\").when(); }",
                    ctClass);
            ctClass.addMethod(runtimeMethod);
            ClassFile classFile = ctClass.getClassFile();
            ConstPool constpool = classFile.getConstPool();
            AnnotationsAttribute annotationAttribute = new AnnotationsAttribute(constpool,
                    AnnotationsAttribute.visibleTag);
            // Intended to add jUnit Test annotation "org.junit.Test"
            Annotation annotation = new Annotation("org.junit.Test", constpool);
            annotationAttribute.addAnnotation(annotation);
            // Setting the annotation to runtime created method
            runtimeMethod.getMethodInfo().addAttribute(annotationAttribute);
            Class<?> runtimeClass = ctClass.toClass();
            Object classObject = runtimeClass.newInstance();
            Class[] parameterClass = new Class[] { String.class };
            Method newRuntimeMethod = runtimeClass.getDeclaredMethod("callAllUserEndpoint", parameterClass);
            Object[] actualParams = new Object[] { new String("/dummyEndPont/") };
            newRuntimeMethod.invoke(classObject, actualParams);
            System.out.println("List number of Annotation available in Runtime Method : "
                    + newRuntimeMethod.getAnnotations().length);
            System.out.println("List number of Annotation available in Runtime Class : "
                    + classObject.getClass().getAnnotations().length);
        } catch (CannotCompileException e) {
            e.printStackTrace();
        } catch (InstantiationException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (NoSuchMethodException e) {
            e.printStackTrace();
        } catch (SecurityException e) {
            e.printStackTrace();
        } catch (IllegalArgumentException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        }
    }
}

В обоих случаях выводится ноль для аннотации на уровне метода и класса.

Я ценю ваши взгляды на решение этой проблемы при добавлении аннотаций на уровне классов и методов?

0 ответов

Другие вопросы по тегам