简体   繁体   中英

IntelliJ IDEA: execute selected fragment of code

Sometimes there is a need to quickly test some expression's output. It would be convenient to execute selected fragment and see the result instantly in System.out without running project's main() method.

Is there some workaround for IntelliJ to provide this feature?

I have a project called "untitled" where I copy-paste the code into and run it there. I have classes which have this template setup already.

Another approach is to debug your code and "evaluate expression". You can give it any snippet of code. ie. it doesn't even have to be a statement.

Use a test framework like JUnit. If its maven, add a dependency to your pom.xml:

<dependency>
    <groupId>junit</groupId>
    <artifactId>junit</artifactId>
    <version>4.11</version>
    <scope>test</scope>
</dependency>

Then, alongside to your project/src/main/java/mypkg/MyClass.java , add a new path: src/test/java/mypkg/MyClassTest.java Inside add a function, call it whatever you like. Add @Test annotation to it, and right-click to execute it.

@Test
public void testA() {
...
}

JUnit is very good practice to your java development applications, as you can test your code carefully and also run small fragments of code quickly. The bonus is that you have your classes and all your deps in your tests to quickly use them as well

The easiest way is just to stop a debug before what you are trying to test, press ALT + F8 and execute the expression on the window that appears.

You are going to have access to everything declared to that point, so you can execute anything without changing the state of your code.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM