PsiDirectory (Project project, Module currentModule, PsiDirectory[] directories, List<VirtualFile> roots) { List<PsiDirectory> dirs = new ArrayList<>(); PsiManager psiManager = PsiManager.getInstance(project); for (VirtualFile file : ModuleRootManager.getInstance(currentModule).getSourceRoots(JavaSourceRootType.TEST_SOURCE)) { final PsiDirectory dir = psiManager.findDirectory(file); if (dir != null) { dirs.add(dir); } } if (!dirs.isEmpty()) { for (PsiDirectory dir : dirs) { final String dirName = dir.getVirtualFile().getPath(); if (dirName.contains("generated")) continue; return dir; } return dirs.get(0); } for (PsiDirectory dir : directories) { final VirtualFile file = dir.getVirtualFile(); for (VirtualFile root : roots) { if (VfsUtilCore.isAncestor(root, file, false)) { final PsiDirectory rootDir = psiManager.findDirectory(root); if (rootDir != null) { return rootDir; } } } } return ModuleManager.getInstance(project) .getModuleDependentModules(currentModule) .stream().flatMap(module -> ModuleRootManager.getInstance(module).getSourceRoots(JavaSourceRootType.TEST_SOURCE).stream()) .map(root -> psiManager.findDirectory(root)).findFirst().orElse(null); }