Skip to content

Instantly share code, notes, and snippets.

@noynaert
Last active October 2, 2017 21:51
Show Gist options
  • Save noynaert/72d3c53bbea9345991d2acf16c0ff289 to your computer and use it in GitHub Desktop.
Save noynaert/72d3c53bbea9345991d2acf16c0ff289 to your computer and use it in GitHub Desktop.
Brutally simple tutorial on using JUnit4 in Intellij with Java

JUnit testing in Intellij

This is a brutally simple introduction to unit testing in Intellij

General setup

  • 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.

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"

Set up the first test

  • 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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment