Skip to content

Commit

Permalink
fix: toStringWithImports works even with no position (#3110)
Browse files Browse the repository at this point in the history
  • Loading branch information
monperrus authored and nharrand committed Sep 19, 2019

Verified

This commit was signed with the committer’s verified signature.
slarse Simon Larsén
1 parent eddd948 commit eef9133
Showing 2 changed files with 10 additions and 3 deletions.
Original file line number Diff line number Diff line change
@@ -12,6 +12,7 @@
import spoon.reflect.code.CtBlock;
import spoon.reflect.declaration.CtAnnotation;
import spoon.reflect.declaration.CtAnnotationType;
import spoon.reflect.declaration.CtCompilationUnit;
import spoon.reflect.declaration.CtConstructor;
import spoon.reflect.declaration.CtExecutable;
import spoon.reflect.declaration.CtField;
@@ -991,8 +992,8 @@ public boolean isArray() {
@Override
public String toStringWithImports() {
DefaultJavaPrettyPrinter printer = (DefaultJavaPrettyPrinter) getFactory().getEnvironment().createPrettyPrinter();
//this call applies print validators, which modifies model before printing
//and then it prints everything including package and potentially imports
return printer.printCompilationUnit(this.getPosition().getCompilationUnit());
CtCompilationUnit cu = getFactory().createCompilationUnit();
cu.addDeclaredType(this);
return printer.printCompilationUnit(cu);
}
}
6 changes: 6 additions & 0 deletions src/test/java/spoon/test/ctClass/CtClassTest.java
Original file line number Diff line number Diff line change
@@ -31,6 +31,7 @@
import static spoon.testing.utils.ModelUtils.buildClass;
import static spoon.testing.utils.ModelUtils.canBeBuilt;

import java.io.File;
import java.util.Set;

import org.junit.Test;
@@ -261,6 +262,11 @@ public void toStringWithImports() {
" }" + newLine +
" }.compare(1, 2);" + newLine +
"}", aClass2.toStringWithImports());

// contract: toStringWithImports works with a new class with no position
assertEquals("package foo;" + newLine +
"import java.io.File;" + newLine +
"class Bar extends File {}", launcher2.getFactory().createClass("foo.Bar").setSuperclass(launcher2.getFactory().Type().get(File.class).getReference()).toStringWithImports());
}

@Test

0 comments on commit eef9133

Please sign in to comment.