JUnit test case example in Java
We are already familiar with the JUnit testing framework. It is used to perform unit testing in Java. The JUnit test case is the set of code that ensures whether our program code works as expected or not.
In Java, there are two types of unit testing possible, Manual testing and Automated testing. Manual testing is a special type of testing in which the test cases are executed without using any tool. Unlike manual testing, automated testing is not possible without supporting any tool.
The org.junit package provides several classes and packages, which helps us to ensure whether our code provides the expected output or not. These packages and classes are Assert, After, Before, and Test, etc.
We will use the eclipse tool to test the java code. We first create the java code which we want to test, and after that, we will write the test class or test case for our Java code.
Let's take the example of a JUnit test case to understand how testing is actually performed in Java.
We have created three java classes, i.e., JunitTestCaseExample.java, TestJunitTestCaseExample.java, and TestRunner.java. In the JunitTestCaseExample.java class, we created the code which we want to test. In this class, we create a list of names and four methods to add an element, remove an element, get the list's size, and remove all elements from the list.
In the TestJunitTestCaseExample.java, we write the test cases for the JunitTestCaseEample.java class. We create an object of the JunitTestCaseExample.java class, and by using its object, we will test all its methods. We use the assertEquals() method to check the actual result with the expected output.
We create the TestRunner.java class to execute the test cases. It contains the main() method in which we run the TestJunitTestCaseExample.java class using the runClasses() method of the JUnitCore. In this method, we pass the class file of the TestJunitTestCaseExample.java. The result returned by the runClasses() method will store into the result variable of type Result.
Now, we will run the TestRunner.java class to execute the test cases. We will get the output true when the test cases are passed and false when the test cases are not passed.
Next TopicList of logical programs in Java