Ananta
Ananta Almost a Computer Engineer, author of Go Woogle, I write about tech and tutorials.

4. First JUnit Test


4. First JUnit Test

Simple JUnit code that tests addition function

  1. Create a new java class src > New > Class Alt
  2. Name it. You can skip selecting public static void main(String[] args) method checkbox. Don’t forget to name file same as class name.

Alt

  1. Code
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
import org.junit.Test;
//to test junit config
public class junitTest {
	@Test   //gets executed everytime we run junit program
	public void test1() {
		if (add(10,3)==15) {
			System.out.println("Pass");
		}else {
			System.out.println("Fail");
		}
	}
	@Test   //gets executed everytime we run junit program
	public void test2() {
		if (add(10,5)==15) {
			System.out.println("Pass");
		}else {
			System.out.println("Fail");
		}
	}
	public int add(int x, int y){   //simple addition function returns addition of two numbers
		return x+y;
	}
}

There is no main method in this code because JUnit does not require you to compulsorily have a main method in java code. Here’s a gist version.

Alt

  1. Run as JUnit test to run it and get output in JUnit panel.

Alt

  1. Output

Everything went well that is why we do not have errors in execution and both tests ran correctly. The Image Below shows Expected Output of the given code.

Alt

Github Repo

Here’s Link to My YouTube Channel. Go Woogle