Search in sources :

Example 1 with ArrayAccessTemplate

use of spoon.test.template.testclasses.ArrayAccessTemplate in project spoon by INRIA.

the class TemplateTest method testTemplateArrayAccess.

@Test
public void testTemplateArrayAccess() throws Exception {
    // contract: the template engine supports substitution of arrays of parameters.
    Launcher spoon = new Launcher();
    spoon.addTemplateResource(new FileSystemFile("./src/test/java/spoon/test/template/testclasses/ArrayAccessTemplate.java"));
    spoon.buildModel();
    Factory factory = spoon.getFactory();
    CtClass<?> resultKlass = factory.Class().create("Result");
    CtClass<?> templateClass = factory.Class().get(ArrayAccessTemplate.class);
    // create array of template parameters, which contains CtBlocks
    TemplateParameter[] params = templateClass.getMethod("sampleBlocks").getBody().getStatements().toArray(new TemplateParameter[0]);
    new ArrayAccessTemplate(params).apply(resultKlass);
    CtMethod<?> m = resultKlass.getMethod("method");
    // check that both TemplateParameter usages were replaced by appropriate parameter value and that substitution which miss the value is silently removed
    assertEquals(2, m.getBody().getStatements().size());
    assertTrue(m.getBody().getStatements().get(0) instanceof CtBlock);
    assertEquals("int i = 0", ((CtBlock) m.getBody().getStatements().get(0)).getStatement(0).toString());
    assertTrue(m.getBody().getStatements().get(1) instanceof CtBlock);
    assertEquals("java.lang.String s = \"Spoon is cool!\"", ((CtBlock) m.getBody().getStatements().get(1)).getStatement(0).toString());
    // check that both @Parameter usage was replaced by appropriate parameter value
    CtMethod<?> m2 = resultKlass.getMethod("method2");
    assertEquals("java.lang.System.out.println(\"second\")", m2.getBody().getStatement(0).toString());
    // check that substitution by missing value correctly produces empty expression
    assertEquals("java.lang.System.out.println(null)", m2.getBody().getStatement(1).toString());
}
Also used : TemplateParameter(spoon.template.TemplateParameter) CtBlock(spoon.reflect.code.CtBlock) ArrayAccessTemplate(spoon.test.template.testclasses.ArrayAccessTemplate) Launcher(spoon.Launcher) Factory(spoon.reflect.factory.Factory) FileSystemFile(spoon.support.compiler.FileSystemFile) Test(org.junit.Test)

Aggregations

Test (org.junit.Test)1 Launcher (spoon.Launcher)1 CtBlock (spoon.reflect.code.CtBlock)1 Factory (spoon.reflect.factory.Factory)1 FileSystemFile (spoon.support.compiler.FileSystemFile)1 TemplateParameter (spoon.template.TemplateParameter)1 ArrayAccessTemplate (spoon.test.template.testclasses.ArrayAccessTemplate)1