Search in sources :

Example 1 with CtTargetedExpression

use of spoon.reflect.code.CtTargetedExpression in project Ex2Amplifier by STAMP-project.

the class MainGenerator method removeNonStaticElement.

private static void removeNonStaticElement(final CtMethod<?> mainMethod, final CtType testClass) {
    final CtBlock<?> body = mainMethod.getBody();
    final Factory factory = mainMethod.getFactory();
    // 1 create a local variable of the test class
    final CtLocalVariable localVariableOfTestClass = factory.createLocalVariable(testClass.getReference(), Character.toLowerCase(testClass.getSimpleName().charAt(0)) + testClass.getSimpleName().substring(1), factory.createConstructorCall(testClass.getReference()));
    // 2 invoke setUp(@Before) at the begin if present
    final CtTry wrappedBefore = wrapInTryCatchMethodWithSpecificAnnotation(testClass, factory, localVariableOfTestClass, "org.junit.Before");
    if (wrappedBefore != null) {
        body.insertBegin(wrappedBefore);
    }
    // 3 invoke tearDown(@After) at the end of the block
    final CtTry wrappedAfter = wrapInTryCatchMethodWithSpecificAnnotation(testClass, factory, localVariableOfTestClass, "org.junit.After");
    if (wrappedAfter != null) {
        body.insertEnd(wrappedAfter);
    }
    // 4 replaces all non-static accesses to accesses on the local variable created at the first step
    body.getElements(new TypeFilter<CtTargetedExpression>(CtTargetedExpression.class) {

        @Override
        public boolean matches(CtTargetedExpression element) {
            return element.getTarget() instanceof CtThisAccess;
        }
    }).stream().map(CtTargetedExpression::getTarget).forEach(target -> target.replace(factory.createVariableRead(localVariableOfTestClass.getReference(), false)));
    body.insertBegin(localVariableOfTestClass);
}
Also used : Factory(spoon.reflect.factory.Factory) CtTargetedExpression(spoon.reflect.code.CtTargetedExpression) CtThisAccess(spoon.reflect.code.CtThisAccess) TypeFilter(spoon.reflect.visitor.filter.TypeFilter) CtTry(spoon.reflect.code.CtTry) CtLocalVariable(spoon.reflect.code.CtLocalVariable)

Aggregations

CtLocalVariable (spoon.reflect.code.CtLocalVariable)1 CtTargetedExpression (spoon.reflect.code.CtTargetedExpression)1 CtThisAccess (spoon.reflect.code.CtThisAccess)1 CtTry (spoon.reflect.code.CtTry)1 Factory (spoon.reflect.factory.Factory)1 TypeFilter (spoon.reflect.visitor.filter.TypeFilter)1