How to create unit tests in eclipse?
Last Updated :
29 Jul, 2024
Unit testing, also known as component testing, involves testing small pieces of code to ensure that their actual behavior matches the expected behavior. Eclipse, a widely used IDE for Java development, is also commonly used for testing purposes. In Java, JUnit is the preferred framework for unit testing. During unit testing, we examine individual components and write tests for them. Mocking libraries can be utilized to test CRUD operations effectively. Eclipse provides an excellent user interface for writing and running unit tests, making the process more efficient.
Prerequisites
- Ensure you have Eclipse IDE installed.
- JDK is installed.
How to Create Unit Tests in Eclipse?
Step-1: Create a simple Spring Boot application using a spring initializer with the configurations shown below:
Create ApplicationAfter this our pom.xml looks like
XML
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>3.3.1</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.example</groupId>
<artifactId>UnitTestExample</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>UnitTestExample</name>
<description>How to Create unit Test in Eclipze</description>
<url/>
<licenses>
<license/>
</licenses>
<developers>
<developer/>
</developers>
<scm>
<connection/>
<developerConnection/>
<tag/>
<url/>
</scm>
<properties>
<java.version>17</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
<scope>runtime</scope>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
Step 2: Create Class for Testing
For creating a basic test, we will create a simple controller for normal Arithmetic operation. In which we will have 4 methods for each basic operations. The code for the Class looks like:
Java
public class Operations {
public Integer Add(int a, int b) {
return a+b;
}
public Integer Subtract(int a, int b) {
return a-b;
}
public Integer Divide(int a, int b) {
if(b==0)
throw new ArithmeticException("Divide By Zero");
return a/b;
}
public Integer Multiply(int a, int b) {
return a*b;
}
}
Now, we will use test this four methods in Unit Tests.
Step: 3 Add JUnit Dependency
For testing in Java, we generally use the Junit test library. Junit provides us annotations and using that we can create tests. The goal of unit testing is to assert the program logic using the assertion methods provided by it. Also, it gives us the annotations for defining the test and classes for easy creation of tests.
For using Junit in our Application we need to add dependency for it in pom.xml.
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<scope>test</scope>
</dependency>
Step: 4 Create Unit Test Class
Now in Test Folder under src, we will create a package and in that we will create one class for writing Junit Tests. The folder structure is shown below:
Folder to Create Unit TestFor Creating class we will Right Click on Package > New > Other. It will prompt the window to select the template of the class we want to create.
Create Unit TestIn the window, we will see the Search option and in that type Junit and below we can see two option. One for Suite and one for Class. Select the Test class from here.
Junit Test WizardAfter this, we will have a window to name the class, package version of Junit. Enter the details in that.
Configuration for Junit TestAfter creating a class it will give us three basic methods.
Java
import static org.junit.jupiter.api.Assertions.*;
import org.junit.Assert;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import com.example.UnitTestExample.Controllers.Operations;
class OperationsTest {
//This Method is Called before any Method
@BeforeAll
static void setUpBeforeClass() throws Exception {
}
//This Method is Called for any setup for any test.
@BeforeEach
void setUp() throws Exception {
}
//Actual Test Method
@Test
void test() {
}
}
This methods will execute according to their annotations. Annotations make test methods more readable and easier to understand. They clearly indicate the role of each method, reducing the need for boilerplate code and comments. Annotations like @Test, @Before, @After, @BeforeClass, and @AfterClass help JUnit identify and execute test methods automatically. This eliminates the need for manual test setup and teardown processes. The sequence in which method will execute are:
- BeforeAll - This will get executed before any test executes
- BeforeForEach - This will execute before every test.
- Test - This is the method in which Testing code goes.
Step 5: Create Unit Test
In the above methods in Before ForEach, we can create a instance. So we will create a instance of Operation class in that and in Test, we will create a test for the Add Method.
Java
import static org.junit.jupiter.api.Assertions.*;
import org.junit.Assert;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import com.example.UnitTestExample.Controllers.Operations;
class OperationsTest {
Operations operations;
//This method will get called before every test method.
//So that every test gets new instance of Operations
@BeforeEach
void setUp() throws Exception {
operations = new Operations();
}
@Test
void testAdd() {
int a = 5;
int b = 6;
Integer expected = 11;
//This will give us the actual result which comes from the code.
Integer actual = operations.Add(a, b);
//Using Assert we can find that whether the actual and Expected outcome are same.
Assert.assertEquals(expected, actual);
}
}
Step: 6 Execute Unit Test
Now click right on the class and you will see the Run As Button in that we can see the option to run JUnit test click on that and new window stating Junit will get open.
Run Unit TestJunit Test Runner Window:
Result of Junit TestClick on the Run Button and the test will get Executed. And you will see the Green Color bar stating that Test Executed Successfully.
Difference Between @BeforeAll, @BeforeEach and @Test
Parameters | @BeforeAll | @BeforeEach | @Test |
---|
Purpose | Sets up resources that need to be initialized once before all tests in the class | Sets up resources or state before each individual test method | Contains the actual test code that verifies specific functionality |
---|
Execution Timing | Runs once before all tests | Runs before each test method | Runs each test method |
---|
Method Type | Static method | Instance method | Instance method |
---|
Usage | Initializing shared resources, setting up database connections | Resetting state, initializing fresh objects for each test | Writing test cases for specific functionalities or behaviors |
---|
Conclusion
Eclipse have a integrated runner and support for Junit and thus we have used that to create a test with that. You can learn more about Unit testing and JUnit. Also Junit can be used for Frontend and Backend. For backend we can test our backend logic while in frontend we can use Selenium with Junit.