PsiUtil.resolveClassInType not work in unit tests (testFramework)

Hi,

I try to write some unit test for my inspections.
Basically, it works. But now I run in some issues. For example, PsiUtil.resolveClassInType always return null.
In "production" all works as expected (resolveClassInType can find the PsiClass, in my example the BaseStream),
but not in my unit test.

My Inspection looks like this:

public class MyInspection extends BaseJavaBatchLocalInspectionTool {
  public PsiElementVisitor buildVisitor(ProblemsHolder holder, boolean isOnTheFly) {
    return new JavaElementVisitor() {
      public void visitMethodCallExpression(PsiMethodCallExpression expression) {
        PsiReferenceExpression expr = expression.getMethodExpression();
        PsiExpression quali = expr.getQualifierExpression();
        if (null == quali) {
          return;
        }
        PsiType type = quali.getType();
        if (null == type) {
          return;
        }
        PsiClass clazz = PsiUtil.resolveClassInType(type);
        if (null == clazz) {
          System.out.println("NOT OK");
          return;
        }
        System.out.println("ok");
        // [..] more code here
      }
    };
  }
}



Unit test:

public class MyInspectionTest extends InspectionTestCase {

  protected String getTestDataPath() {
    return new File(".", "test/data/inspection").getAbsolutePath();
  }

  protected void setupRootModel(String testDir, VirtualFile[] sourceDir, String jdkName) {
    super.setupRootModel(testDir, sourceDir, jdkName);
    VirtualFile projectDir = LocalFileSystem.getInstance().findFileByPath(testDir);
    VirtualFile test = projectDir.findChild("test");
    if (test != null) PsiTestUtil.addSourceRoot(myModule, test, true);
  }

  protected AnalysisScope createAnalysisScope(VirtualFile sourceDir) {
    return new AnalysisScope(myProject);
  }

  public void testSimple() throws Exception {
    doTest();
  }

  private void doTest() throws Exception {
    MyInspection i = new MyInspection();
    doTest("myInspection/" + getTestName(true), new LocalInspectionToolWrapper(i), "java 1.8");
  }
}



Unit test file:

public class A {
  void test(java.util.stream.BaseStream s) {
    s.parallel().close();
  }
}


I think it is just some configuration wrong/missing ?

Thanks in advance!

2 comments
Comment actions Permalink

By default, the tests run with a stripped-down version of JDK 1.7. You need to override getTestProjectJdk() in your test and to return IdeaTestUtil.getMockJdk18().

0
Comment actions Permalink

Hello Dmitry,

Thanks for this hint! I had to do some more changes but now it works as expected

Best Regards
0

Please sign in to leave a comment.