public BodyDeclaration getTreeNode() { // System.out.println("Building Method " + node.getName()); String finalName = name + type.name() + Config.get().getTestMethodSuffix(); MethodDeclaration result = new MethodDeclaration(ModifierSet.PUBLIC, new VoidType(), finalName); result.setComment( new BlockComment( "\n\t\tGenerated Unity test\n\t\t" + name + " - " + type.name() + " test." + "\n\t")); AnnotationExpr anno = new MarkerAnnotationExpr(new NameExpr("Test")); List<AnnotationExpr> annoList = new ArrayList<>(); annoList.add(anno); result.setAnnotations(annoList); BlockStmt body = new BlockStmt(); List<Statement> statements = new ArrayList<>(); statements.add(instance.getStatement()); body.setStmts(statements); result.setBody(body); // Set any mocks // Set instance // Set call parameters // Set call result // Set assertions return result; }
void changeTypeContext(ResolutionContext old, ResolutionContext new_, MethodDeclaration m) { m.setType(changeTypeContext(old, new_, m.getType())); m.setBody( new BlockStmt( Collections.singletonList( new ThrowStmt( new ObjectCreationExpr( null, new ClassOrInterfaceType("UnsupportedOperationException"), Collections.emptyList()))))); NodeUtil.forChildren( m, node -> { Expression scope = node.getScope(); // TODO: Currently guesses that it's a type name if first character is uppercase. // Should check for fields/variables which match instead if (scope instanceof NameExpr && Character.isUpperCase(((NameExpr) scope).getName().charAt(0))) { String name = ((NameExpr) scope).getName(); node.setScope(ASTHelper.createNameExpr(new_.typeToString(old.resolve(name)))); } }, MethodCallExpr.class); NodeUtil.forChildren( m, node -> node.setType(changeTypeContext(old, new_, node.getType())), VariableDeclarationExpr.class); NodeUtil.forChildren( m, node -> node.setType(changeTypeContext(old, new_, node.getType())), TypeExpr.class); NodeUtil.forChildren( m, node -> node.setType(changeTypeContext(old, new_, node.getType())), com.github.javaparser.ast.body.Parameter.class); }
// This generates all the test methods of the class, given a starting node private static List<BodyDeclaration> generateTestMethods(RoundTripPathTreeNode node) { final List<BlockStmt> bodies = generateTestBodies(node); final List<BodyDeclaration> methods = new ArrayList<BodyDeclaration>(); int i = 0; for (BlockStmt body : bodies) { final MethodDeclaration method = new MethodDeclaration( ModifierSet.PUBLIC, new VoidType(), "conformanceTest" + i++, Collections.<Parameter>emptyList()); method.getAnnotations().add(new MarkerAnnotationExpr(new NameExpr("Test"))); method.setBody(body); methods.add(method); } return methods; }