Add test for Java 'this' keyword typeresolution

This commit is contained in:
Bendegúz Nagy
2017-05-29 02:19:17 +02:00
parent 872718a0dd
commit e75cf1b55c
4 changed files with 116 additions and 29 deletions

View File

@ -6,7 +6,14 @@ package net.sourceforge.pmd.typeresolution;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
import net.sourceforge.pmd.lang.ast.Node;
import net.sourceforge.pmd.lang.java.ast.ASTPrimaryExpression;
import net.sourceforge.pmd.lang.java.ast.ASTPrimaryPrefix;
import net.sourceforge.pmd.typeresolution.testdata.ThisExpression;
import org.jaxen.JaxenException;
import org.junit.Test;
import net.sourceforge.pmd.lang.LanguageRegistry;
@ -16,6 +23,8 @@ import net.sourceforge.pmd.lang.java.ast.ASTCompilationUnit;
import net.sourceforge.pmd.typeresolution.testdata.UsesJavaStreams;
import net.sourceforge.pmd.typeresolution.testdata.UsesRepeatableAnnotations;
import static org.junit.Assert.assertEquals;
public class ClassTypeResolverJava8Test {
@Test
@ -28,6 +37,37 @@ public class ClassTypeResolverJava8Test {
ASTCompilationUnit acu = parseAndTypeResolveForClass18(UsesRepeatableAnnotations.class);
}
@Test
public void testThisExpression() throws JaxenException {
ASTCompilationUnit acu = parseAndTypeResolveForClass18(ThisExpression.class);
List<ASTPrimaryExpression> expressions = convertList(
acu.findChildNodesWithXPath("//VariableInitializer/Expression/PrimaryExpression"),
ASTPrimaryExpression.class);
List<ASTPrimaryPrefix> prefixes = convertList(
acu.findChildNodesWithXPath("//VariableInitializer/Expression/PrimaryExpression/PrimaryPrefix"),
ASTPrimaryPrefix.class);
int index = 0;
assertEquals(ThisExpression.class, expressions.get(index).getType());
assertEquals(ThisExpression.class, prefixes.get(index++).getType());
assertEquals(ThisExpression.PrimaryThisInterface.class, expressions.get(index).getType());
assertEquals(ThisExpression.PrimaryThisInterface.class, prefixes.get(index++).getType());
// Make sure we got them all
assertEquals("All expressions not tested", index, expressions.size());
assertEquals("All expressions not tested", index, prefixes.size());
}
private static <T> List<T> convertList(List<Node> nodes, Class<T> target) {
List<T> converted = new ArrayList<>();
for (Node n : nodes) {
converted.add(target.cast(n));
}
return converted;
}
private ASTCompilationUnit parseAndTypeResolveForClass18(Class<?> clazz) {
return parseAndTypeResolveForClass(clazz, "1.8");
}

View File

@ -0,0 +1,15 @@
package net.sourceforge.pmd.typeresolution.testdata;
public class ThisExpression {
public void foo() {
((Runnable) (() -> { ThisExpression b = this; })).run();
}
public interface PrimaryThisInterface {
default void foo() {
PrimaryThisInterface a = this;
}
}
}