4. First JUnit Test
Simple JUnit code that tests addition function
- Create a new java class
src > New > Class
- Name it.
You can skip selecting
public static void main(String[] args)
method checkbox. Don’t forget to name file same as class name.
- 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.
- Run as JUnit test to run it and get output in JUnit panel.
- 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.
Here’s Link to My YouTube Channel. Go Woogle