use of spoon.reflect.code.CtReturn in project spoon by INRIA.
the class EqualTest method testEqualsEmptyException.
@Test
public void testEqualsEmptyException() throws Exception {
Factory factory = new Launcher().createFactory();
String realParam1 = "\"\"";
String content = "" + "class X {" + "public Object foo() {" + " Integer.getInteger(" + realParam1 + ");" + " return \"\";" + "}};";
SpoonModelBuilder builder = new JDTSnippetCompiler(factory, content);
try {
builder.build();
} catch (Exception e) {
e.printStackTrace();
fail("Unable create model");
}
CtClass<?> clazz1 = (CtClass<?>) factory.Type().getAll().get(0);
CtMethod<?> method = (CtMethod<?>) clazz1.getMethods().toArray()[0];
CtInvocation<?> invo = (CtInvocation<?>) method.getBody().getStatement(0);
CtLiteral<?> argument1 = (CtLiteral<?>) invo.getArguments().get(0);
assertEquals(realParam1, argument1.toString());
CtReturn<?> returnStatement = (CtReturn<?>) method.getBody().getStatement(1);
CtLiteral<?> returnExp = (CtLiteral<?>) returnStatement.getReturnedExpression();
assertEquals(realParam1, returnExp.toString());
try {
assertEquals(argument1, returnExp);
} catch (Exception e) {
fail(e.getMessage());
}
}
use of spoon.reflect.code.CtReturn in project spoon by INRIA.
the class CompilationTest method compileTest.
@Test
public void compileTest() throws Exception {
// contract: the modified version of classes is the one that is compiled to binary code
final Launcher launcher = new Launcher();
launcher.addInputResource("./src/test/resources/noclasspath/Simple.java");
File outputBinDirectory = new File("./target/class-simple");
if (!outputBinDirectory.exists()) {
outputBinDirectory.mkdirs();
}
launcher.setBinaryOutputDirectory(outputBinDirectory);
launcher.getEnvironment().setShouldCompile(true);
launcher.buildModel();
Factory factory = launcher.getFactory();
CoreFactory core = factory.Core();
CodeFactory code = factory.Code();
CtClass simple = factory.Class().get("Simple");
CtMethod method = core.createMethod();
method.addModifier(ModifierKind.PUBLIC);
method.setType(factory.Type().integerPrimitiveType());
method.setSimpleName("m");
CtBlock block = core.createBlock();
CtReturn aReturn = core.createReturn();
CtBinaryOperator binaryOperator = code.createBinaryOperator(code.createLiteral(10), code.createLiteral(32), BinaryOperatorKind.PLUS);
aReturn.setReturnedExpression(binaryOperator);
// return 10 + 32;
block.addStatement(aReturn);
method.setBody(block);
simple.addMethod(method);
launcher.getModelBuilder().compile();
final URLClassLoader urlClassLoader = new URLClassLoader(new URL[] { outputBinDirectory.toURL() });
Class<?> aClass = urlClassLoader.loadClass("Simple");
Method m = aClass.getMethod("m");
Assert.assertEquals(42, m.invoke(aClass.newInstance()));
}
Aggregations