How to load java file into PsiClass that is outside of a project?
I'd like to create a unit test that only tests the Unit Test generation part (without the IJ Gui part). My idea is to prepare some testdata java classes and the let generate the unit tests for them and then check if they are correctly generated.
The problem I have is, that I haven't found a possibility yet how to load a java file (or a text file) into an instance of PsiClass. It can be done by a code similar to the following one, if your code is run within the Itellij Idea gui code and if the file is in the currently open project, which is NOT my case for the test.
VirtualFile vf = LocalFileSystem.getInstance().findFileByIoFile(new File("path\\SimpleClass.java"));
var projects = ProjectManager.getInstance().getOpenProjects();
PsiFile file = PsiManager.getInstance(projects[0]).findFile(vf);
Any code samples or ideas how to achieve this? Or maybe another aproach how to get an instance of PsiClass as a test input?
Thanx in advance.
Please sign in to leave a comment.
Lubos,
You can use
method to create a PsiFIle without dealing with the filesystem.
Thank You for your answer Jakub. The problem with your proposition in my context is that in the Junit test I have no meaningful instance of a project and I get the following error when the createFileFromText(..) method is called:
ERROR: Read access is allowed from event dispatch thread or inside read-action only (see com.intellij.openapi.application.Application.runReadAction())
java.lang.Throwable: Read access is allowed from event dispatch thread or inside read-action only (see com.intellij.openapi.application.Application.runReadAction())
My sample code is:
var projects = ProjectManager.getInstance().getOpenProjects();
String javaFileName = "SimpleClass.java";
// load the java class contents from java text file
List<String> lines = null;
try {
String filePath = "path\\SimpleClass.java";
lines = Files.readAllLines(Paths.get(filePath));
} catch (IOException e) {
e.printStackTrace();
}
String javaFileText = "";
for (String line : lines) {
javaFileText += line;
}
PsiJavaFile psiJavaFile = (PsiJavaFile)PsiFileFactory.getInstance(projects[0]).createFileFromText(javaFileName, javaFileText).getOriginalFile(); // this call fails with exception described above