Search code examples
intellij-ideaintellij-plugin

Plugin that runs tests based on file of user


I am developing a Plugin for IntelliJ for teaching purposes, where students write some code and the teacher can write tests and the students can run those tests and see if they are doing it all correctly. It would be great if I would get the file the user is writing in as a java class so that I can run the functions of that class from within another function and test it as if I would have written it.

What I have as of now:

  1. In the Main Toolbar I have a button, where the students should be able to run the tests. I have a class that extends AnAction, now I have no Idea what I should write in it:

    @Override public void actionPerformed(AnActionEvent e) {

    }
    

I have been going through the IntelliJ documentation for some time now and as by now I do not get any further. I sure hope that the experienced developers that can be found here can manybe give me a hint or two.

Thanks a lot in advance :)


Solution

  • If I understand correctly, the students would be programming within a project within IntelliJ?

    Then you can get the path to the project that they are working on using the AnActionEvent event.

    Project project = event.getProject();
    String projectBasePath = project.getBasePath();
    

    You could use this to send the entire src folder to your computer and do what it is that you need to do there?

    But, it also sounds like you would want the students to run the test functions on their side via the plugin. In that case, one option that I know of is to again use the project.getBasePath(), or get them to select a file using a GUI, and then use ProcessBuilder to compile, run, test, etc their Java classes. You can run any Windows / shell command this way and pipe the output into the IDE, or your own tool window.

    public void actionPerformed(AnActionEvent event) {
    
        Project project = event.getProject();
        String projectBasePath = project.getBasePath();
    
        ProcessBuilder pb = new ProcessBuilder();
        pb.directory(projectBasepath);
        pb.command("cmd", "/k", "javac src\*.java")
    
        pb.redirectErrorStream(true);
    
        Process process = pb.start();
    
        BufferedReader reader = new BufferedReader(newInputStreamReader(process.getInputStream()));
    
        String line;
        while ((line = reader.readLine()) != null) {
            System.out.println(line);
        }
    
        int exitCode = process.waitFor();
    
        System.out.println("\nExited with error code : " + exitCode);
    
        ... // anything else you need to do
    }
    

    Let me know if this makes sense - maybe I can help you out more if you give me more specific questions.