This is a brutally simple introduction to unit testing in Intellij
- Create a new Project
- Create a folder called "tests" in the project. It should be at the same level as "src" for this simple example.
- Click on file
- Click on "Project Structure"
- Click on "Modules" in the left pane
- Click on "Sources" in the right pane
- Select "tests"
- On the line that starts "Mark as" select "Texts"
- Click on Apply and OK.
- Click on "Project Structure"
Go into your Main{ } class and enter the following: (You might have a different class name) public class Main {
public static void main(String[] args) {
System.out.printf("%d, %d\n",0,square(0));
System.out.printf("%d, %d\n",-1,square(-1));
System.out.printf("%d, %d\n",1,square(1));
System.out.printf("%d, %d\n",85,square(85));
}
public static int square(int number){
return number*number;
}
}
Right-click on Main and select "Run"
- Click on the function name "square"
- hit Ctrl-Shift-T
- Select "Create New Test.."
- Change "Groovy JUnit" to JUnit4
- Hit "Fix"
- Hit "OK"
- Click on the check box next to "square" and hit OK.
I suggest you type the following line up with the import
import static org.junit.Assert.*;
Type the following into the class:
public class MainTest {
@Test
public void square() throws Exception {
assertEquals(4,Main.square(2));
}
}
At this point note that you have two methods called "square" in your project. One is Main.square( ... ) and the other is MainTest.square(...) If you want to simplify things, change square in TestMain to "TestSquare"
public class MainTest {
@Test
public void TestSquare() throws Exception {
assertEquals(4,Math.square(2));
}
}
Right click on the "TestMain" class. Click "Run" You should get a green bar
Notice that if you click on "Run" on the top menu and then "Run.." you have two options for what to run.