shortenClassReferences does not "shorten" java.util.Collections
Hello.
I am writing an intention that is adding some statements, these statements uses types from external library and some from the JDK (such as `java.util.Collections`). The types from the external libraries are imported correctly, but the types coming from the JDK are not.
At some point the intention adds this statement
var stmt = JavaPsiFacade.getElementFactory(project).createStatementFromText("foo.bar(java.util.Collections.singleton(\"\"))", null)
Then the invoke method of the intention terminates with these lines on the `PsiCodeBlock` that received the statements :
var javaStyleManager = JavaCodeStyleManager.getInstance(project);
var formatter = CodeStyleManager.getInstance(project);
javaStyleManager.shortenClassReferences(formatter.reformat(catchBlock));
The test is written this way :
public void testCatch() {
myFixture.configureByFile("before" + name + ".java");
assertTrue(action.isAvailable(getProject(), getEditor(), getFile()));
myFixture.launchAction(action);
myFixture.checkResultByFile("after" + name + ".java");
}
@Override
protected @NotNull LightProjectDescriptor getProjectDescriptor() {
return new DefaultLightProjectDescriptor() {
@Override
public void configureModule(@NotNull Module module, @NotNull ModifiableRootModel model, @NotNull ContentEntry contentEntry) {
super.configureModule(module, model, contentEntry);
String jarPath = new File("src/test/testData/jars").getAbsolutePath();
PsiTestUtil.addLibrary(
model,
"libExt",
jarPath,
"libA.jar",
"libB.jar");
}
};
}
The test extends `LightJavaCodeInsightFixtureTestCase`.
The test fails because `java.util.Collections` does not appear in the imports. I have searched on this forum similar problem. The only thing that seemed to work is a comment from Yann Cebron .
If the fixture in the test is configured with
myFixture.addClass("package java.util; public class Collections {}");
The intention correctly add the imports of `java.util.Collections`.
While this work, I wonder if I didn't miss something in the test setup, maybe around the `LightProjectDescriptor`. Thanks in advance for your support.
Please sign in to leave a comment.
This is expected behavior, as JDK classes are not automatically available in tests but mockJDK must be configured. See https://plugins.jetbrains.com/docs/intellij/tests-prerequisites.html#set-the-run-configuration-parameters
Ah ok! That makes sense thank you !
Do you think the alternative I took with
is acceptable if the code only require a few select type ? I.e it doesn't require the other types that are declared in https://github.com/JetBrains/intellij-community/tree/master/java/mockJDK-1.7 ?
Yes, absolutely.
OK, great ! Thank you again for the fast reply !
🙏