Java Programming Language: JUnit Unit Test Tutorial
Hi everyone, welcome back. Today, we will cover how to write a unit test using JUnit in Java. Unit testing is used to check and validate that a portion of code is working or behaving the way it is supposed to. Unit tests are extremely helpful when it comes to bug fixing and error handling. Let’s go over the basics of unit testing.

Creating a Function to Unit Test
Let’s create a simple function so we can see how to unit test. I’m going to create a mathematical function in a class. This function is going be named “onePlusTwo()” and is going to return 3. See my class and function below:
public class MyUnitTestExample {
public static int onePlusTwo() {
return 3;
}
}
So now that we have a simple function within a class, let’s see how we can unit test this.
Writing a Unit Test for our Function
Now we are going to create a new file for JUnit. I am using New JUnit Jupiter Test, so keep in mind that things may be different if you are using JUnit 4 or JUnit 3. We are now going to write a test to test if our function works correctly:
import static org.junit.jupiter.api.Assertions.*;
import org.junit.jupiter.api.Test;class MyUnitTestExampleTest {
@Test
void test() {
assertEquals(3, MyUnitTestExample.onePlusTwo());
}
}
As we can see in the example above, our new JUnit class is named “MyUnitTestExampleTest.” The ‘Test’ annotation is used to define test cases so JUnit knows what to run as tests.
The assertEquals() function is what is used to see if we are getting the expected result from our function that we are testing. In this case, we are testing if the ‘onePlusTwo()’ function in the ‘MyUnitTestExample’ class results in a 3 being returned, which it should be the case since it is hardcoded.
Let’s run our unit test.

As we can see, we ran one test(we only wrote one test) and it succeeded.
Let’s see what happens if we purposefully make the test fail. I’m going to modify the assertEquals() function to check the return result of our function against a 4 instead of a 3:
@Test
void test() {
assertEquals(4, MyUnitTestExample.onePlusTwo());
}

As you can see in the image above, we have a failure. It also informs you on which test suite and which exact test fails.
Testing a Function with Parameters
Let’s see an example of us testing a function that has parameters. I’m going to write a new function in our class which takes in two integers and returns the sum:
public static int add(int numberA, int numberB) {
return numberA + numberB;
}
Now that this function is written, we’re going to add a new test in our unit test file:
@Test
void test2() {
assertEquals(3, MyUnitTestExample.add(1, 2));
}
We named this ‘test2' and our assertEquals is testing if our add() function will return a 3 with our given parameters, and the test passes.
Conclusion
And that is it on the basics of unit testing and hopefully is enough to help you get started. I hope this helps. Thanks for reading.