How To Setup JUnit Environment For Your First Test?
himanshuseth004
Posted on January 29, 2021
JUnit is a popular Java-based, open-source framework that is primarily used for unit testing. It can be used with Selenium for testing websites and web applications. Annotations in JUnit are used for identifying test methods. A variety of assertions, grouping tests into test suites, and ease offered in maintaining tests are the major reasons for JUnit’s popularity for cross browser testing for Java development.
At the time of writing this article, JUnit had a market share of 7.64 percent compared to other frameworks like Apache JMeter, TestNG, etc.
By the end of this blog, you should be comfortable with setting up JUnit on your machine and running JUnit with Eclipse and JUnit with IntelliJ.
How To Download, Install, And Setup JUnit?
JUnit is a Java-based automation framework, which means that the Java Development Kit (JDK) needs to be installed before performing further steps of the JUnit environment setup process. If you are a Java developer or a QA engineer who writes automation tests with Java, you should have JDK installed on your machine.
If you are just starting with JUnit testing or implementation in Java, you need to have JDK installed on the system. Let’s start with the pre-requisites:
Install Java
For starters, the Java Development Kit (JDK) lets you code and run Java programs. You can have multiple JDK versions on the machine, but it is recommended to use the latest version. Let’s look at installing Java on Windows, an essential step for setting up JUnit for automation testing.
Step 1 – Go to the Java SE (Standard Edition) page and click on JDK Download.
Step 2 – Accept the license agreement to download JDK executable file.
Step 3 – Double-click on the executable to install Java on the system.
Step 4 – Upon installation of Java, append the installation location to the environment variables PATH and CLASSPATH.
We only append the location of /bin to the environment variable PATH.
Alternately, you can also append to PATH by running the following command on the terminal (or command prompt):
PATH = \bin;%PATH%;
The same process should be followed for setting the environment variable CLASSPATH. You should append the path to \lib to CLASSPATH.
Step 5 – The last step is confirming the installation of Java on the machine. Run the command java -version
to verify the same.
With this, the basic requisite for JUnit environment setup is complete.
Setup JUnit Environment
Here we install the latest release of JUnit 4. At the time of this article, the 4.13.1 was the latest stable release of JUnit. Follow the below-mentioned steps to download and install JUnit, the most important step of JUnit environment setup.
Step 1 – Visit the JUnit official site and click on ‘Download and Install’.
Step 2 – Click on junit.jar to redirect the Maven Central repository from where you can download the JUnit jar file.
There is no necessity to download the ‘Hamcrest Core’ jar file since the latest version of the Hamcrest framework consists of a single jar file. This jar file contains the base classes and library that is primarily used for matcher implementations. Further, we would look at how to download the required Hamcrest (v2.2) jar file for JUnit testing.
Step 3 – In the Maven Central Repository, click on the latest version of the JUnit framework (i.e., 4.13.1).
This will open up another page that lets you download the JUnit jar file and provide options to download the Dependencies that can be added to pom.xml. Since we are downloading the JUnit jar on the machine, we would be using that JUnit jar file in pom.xml.
Alternatively, the JUnit 4.13.1 jar file can be downloaded directly from the Maven repository by visiting this link. Keep the JUnit jar file in a specified location (e.g., C:\JUnit).
Step 4 – Hamcrest core jar file is now obsolete. Instead, a single Hamcrest jar file has to be downloaded so that you can execute the JUnit tests in Eclipse, IntelliJ, and on the command line.
Download the Hamcrest (v2.2) jar file from here. Shown below are the snapshots captured from the Maven repository from where we download the Hamcrest jar.
So far, we have downloaded two jar files (JUnit and Hamcrest) on our system. The files are placed in the same directory.
JUNIT (V 4.13.1) | https://repo1.maven.org/maven2/junit/junit/4.13.1/junit-4.13.1.jar |
HAMCREST (V2.2) | https://repo1.maven.org/maven2/org/hamcrest/hamcrest/2.2/hamcrest-2.2.jar |
We placed the JUnit and Hamcrest jar files in the C:\JUnit folder
.
The next step is the JUnit environment setup, i.e., setting the required environment variables for accessing the JUnit framework.
Setup Environment Variables for JUnit
Now that we have downloaded the required jar files on the system, we set the JUNIT_HOME environment variable value.
Step 1 – Create a new System Variable (under the ‘Environment variables’ section).
Under the new System Variable window, enter the following details:
- Variable Name – JUNIT_HOME
- Variable Value – Path to JUnit.jar (i.e., C:\JUnit in our case)
Click on ‘OK’ to set the newly created environment variable. As seen below, JUNIT_HOME is visible in the System variable section.
Setup CLASSPATH Variable for JUnit
Step 1 – In this step, we modify the CLASSPATH environment variable (if it exists) by appending the JUnit jar’s location. If the CLASSPATH environment variable is not available in the system, create a new System Variable with the following details:
- Variable Name – CLASSPATH
- Variable Value – %CLASSPATH%;%JUNIT_HOME%\junit.jar;.;
Click on ‘OK’ to create (or modify) the environment variable CLASSPATH. As seen below, the system variable CLASSPATH is successfully created (or modified) in the system.
We have set the PATH and CLASSPATH environment variables for Java (which was done earlier) and the JUnit framework. With the JUnit environment setup, we look at how to use JUnit with Eclipse and JUnit with IntelliJ IDEs.
How to use JUnit with Eclipse IDE and IntelliJ IDEA?
For demonstrating how to use JUnit and Selenium with popular IDEs like Eclipse and IntelliJ, we take a sample test scenario of performing certain actions on the LambdaTest ToDo Page. Here is the test scenario:
- Navigate to the URL https://lambdatest.github.io/sample-todo-app/ in the latest version of Chrome on Windows 10.
- Click on the web elements with li1 and li2.
- Add a new element to the ToDo list titled Happy Testing at LambdaTest.
- Assert if the new element is not added to the list.
The automation test will be performed on the cloud-based Selenium Grid on LambdaTest. LambdaTest capabilities generator is used for generating the desired browser and platform capabilities. The username and access key required for accessing the Grid can be found on the LambdaTest profile page.
The implementation with JUnit and Selenium remains unchanged, irrespective of the IDE being used. Apart from JUnit and Hamcrest jars (which we have downloaded locally), the remaining dependencies are downloaded dynamically from the Maven repository. These dependencies are added in the Maven pom.xml. You can check our earlier blog for getting started with Maven for Selenium testing.
Note- StoppedByUserException happens when user/script requests to stop the test run then it raised StoppedByUserException.
How to run JUnit from the Eclipse IDE?
Eclipse IDE is primarily used for development using the Java programming language. Let’s kick start with the basics of Eclipse.
What is Eclipse IDE?
Eclipse is a popular Integrated Development Environment (IDE) majorly used for developing applications using Java and other popular languages like C++, PHP, Python, PERL, and more. The functionalities offered by Eclipse IDE can be extended using plugins. The rich set of plugins provided by the Java Development Tools (JDT) project enables Eclipse to be used as a Java IDE. The Eclipse platform and plugins from the Eclipse foundation are released under the Eclipse Public License (EPL). The EPL license ensures that the Eclipse IDE & plugins are free for use.
The first version of Eclipse IDE was released way back in 2006 under the codename ‘Callisto.’ The latest release of Eclipse IDE can be downloaded from the below links:
We recommend downloading Eclipse IDE for EE (or Enterprise) Java Developers, as it comes bundled with more integrations compared to the Eclipse IDE for Java developers.
How to create JUnit tests in Eclipse IDE?
Step 1 – To get started with creating JUnit tests in Eclipse IDE, we create a new Maven Project.
Step 2 – Instead of creating a new workspace, you can select ‘Use default Workspace location’.
Step 3 – Select the default options in the subsequent steps for creating the Maven project.
Step 4 – Enter a relevant Group ID, Artifact ID, Version, and Package in the final step of the project creation. The details should resonate well with the test scenario being tested in the JUnit Test. We entered the following details:
- Group ID – com.test
- Artifact ID – junitdemo
- Version – 0.0.1-SNAPSHOT
- Package – com.test.junitdemo
Click on ‘Finish’ to create the project.
Step 5 – Create a new package named ‘com.test.junitdemo’
under ‘src/test/java’
. Once the package is created, create a new class file named ‘JunitDemo’ under that package.
Shown below is the snapshot from the Eclipse project that we created on our system:
Step 6 – Add the test code that uses cloud-based Selenium Grid for testing.
The following code is added in the newly created file named JUnitDemo.java.
FileName – JunitDemo.java
package com.test.junitdemo;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.*;
import java.net.MalformedURLException;
import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.remote.DesiredCapabilities;
import org.openqa.selenium.remote.RemoteWebDriver;
import java.net.URL;
import org.junit.Assert;
/* JUnit related imports */
import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.*;
public class JUnitDemo {
/* protected static ChromeDriver driver; */
static WebDriver driver = null;
static String URL = "https://lambdatest.github.io/sample-todo-app/";
public static String status = "passed";
/* Details available at https://accounts.lambdatest.com/detail/profile */
static String username = "user-name";
static String access_key = "access-key";
@BeforeClass
public static void SetUpClass() throws MalformedURLException {
DesiredCapabilities capabilities = new DesiredCapabilities();
capabilities.setCapability("build", "[Java] Demonstration of running JUnit tests from Eclipse");
capabilities.setCapability("name", "[Java] Demonstration of running JUnit tests from Eclipse");
capabilities.setCapability("platform", "Windows 10");
capabilities.setCapability("browserName", "Chrome");
capabilities.setCapability("version","latest");
capabilities.setCapability("tunnel",false);
capabilities.setCapability("network",true);
capabilities.setCapability("console",true);
capabilities.setCapability("visual",true);
driver = new RemoteWebDriver(new URL("https://" + username + ":" + access_key + "@hub.lambdatest.com/wd/hub"), capabilities);
/*
* driver = new ChromeDriver();
*/
System.out.println("Started session");
}
@Test
public void test_LT_ToDoApp() throws InterruptedException {
driver.navigate().to(URL);
driver.manage().window().maximize();
try {
/* Let's mark done first two items in the list. */
driver.findElement(By.name("li1")).click();
driver.findElement(By.name("li2")).click();
/* Let's add an item in the list. */
driver.findElement(By.id("sampletodotext")).sendKeys("Happy Testing at LambdaTest");
driver.findElement(By.id("addbutton")).click();
/* Let's check that the item we added is added in the list. */
String enteredText = driver.findElement(By.xpath("/html/body/div/div/div/ul/li[6]/span")).getText();
Assert.assertEquals(enteredText, "LT - Happy Testing at LambdaTest");
if (enteredText.equals("Happy Testing at LambdaTest")) {
System.out.println("Demonstration of running JUnit tests from Eclipse is complete");
}
} catch (Exception e) {
System.out.println(e.getMessage());
}
}
@AfterClass
public static void TearDownClass() {
if (driver != null) {
((JavascriptExecutor) driver).executeScript("lambda-status=" + status);
System.out.println("TearDown is called");
driver.quit();
}
}
}
As seen in the implementation, the following Annotations in JUnit are used for organizing, grouping, and maintaining test cases:
- @BeforeClass – It is used for initializing any object that is used in the test scenario. In our case, we perform the initialization of a new instance of the RemoteWebDriver class. The LambdaTest credentials [i.e., the combination of username and access key] are used for performing the test on the cloud-based Selenium Grid [i.e., @hub.lambdatest.com/wd/hub]
- @test – The test method [test_LT_ToDoApp()] is implemented under this particular annotation. The findElement method in Selenium is used for locating the required web elements on the target page. The click method is used to perform a click action on the searched web element, and the sendKeys method is used to add a new entry in the ToDo list. Assert is raised if the new element is not added to the list.
- @AfterClass – In the TearDownClass method, the WebDriver instance’s resources are released by invoking the quit method offered by Selenium WebDriver.
Step 7 – Point the JRE System library to the latest version of JRE.
JRE System library is automatically added to the Java project in Eclipse. If you have various versions of Java installed on the machine, there is a possibility that the JRE System library might be pointing to the old version of JRE.
- To point the JRE System library to the latest version (or a version of your choice), click on JRE System Library ? Build Path ? Configure Build Path.
- In the newly opened window, click on Java Build Path ? JRE System Library [jdk-xx.x.x] ? Edit Button.
- Select ‘Alternate JRE’ and click on ‘Installed JREs’ to add or edit JRE definitions.
- If the JRE version is not listed in the list, click on ‘Add’ and point to the directory that contains the desired Java version that you intend to use for the compilation process.
- Set the newly added JRE as the ‘default JRE’ for the workspace.
In our case, the latest version of JRE is 15.0.1, and the same was selected for the workspace.
Add JUnit in the Eclipse workspace
This is in continuation to the JUnit environment setup for Eclipse. It is the most important step in JUnit with Eclipse, as we look at different ways to add JUnit support in the Eclipse workspace.
Option A – Setting up pom.xml (to add JUnit, Hamcrest, and other relevant dependencies)
Apart from JUnit and Hamcrest, we need to download other dependencies such as selenium-java, webmanagerdriver, etc. For adding the ‘local’ dependencies (i.e., junit.jar and hamcrest-2.2.jar), the respective jar files’ paths are added under . There are other ways to add local jar files to a Maven project but adding the details in pom.xml is the widely preferred option.
Since JUnit and Hamcrest jar files are outside the project folder, we add those jar files to the project using their absolute paths.
</dependencies>
[...]
<dependency>
<groupId>hamcrest</groupId>
<artifactId>hamcrest</artifactId>
<version>2.2</version>
<scope>system</scope>
<systemPath>C:\JUnit\hamcrest-2.2.jar</systemPath>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.13.1</version>
<scope>system</scope>
<systemPath>C:\JUnit\junit.jar</systemPath>
</dependency>
[...]
</dependencies>
Shown below is the complete pom.xml:
<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 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.test</groupId>
<artifactId>junitdemo</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging>
<name>junitdemo</name>
<url>http://maven.apache.org</url>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>
<dependencies>
<dependency>
<groupId>org.seleniumhq.selenium</groupId>
<artifactId>selenium-java</artifactId>
<version>4.0.0-alpha-6</version>
</dependency>
<dependency>
<groupId>org.seleniumhq.selenium</groupId>
<artifactId>selenium-chrome-driver</artifactId>
<version>4.0.0-alpha-6</version>
</dependency>
<dependency>
<groupId>io.github.bonigarcia</groupId>
<artifactId>webdrivermanager</artifactId>
<version>4.1.0</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-nop</artifactId>
<version>1.7.28</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>hamcrest</groupId>
<artifactId>hamcrest</artifactId>
<version>2.2</version>
<scope>system</scope>
<systemPath>C:\JUnit\hamcrest-2.2.jar</systemPath>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.13.1</version>
<scope>system</scope>
<systemPath>C:\JUnit\junit.jar</systemPath>
</dependency>
</dependencies>
<build>
<!-- <defaultGoal>install</defaultGoal>-->
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.5.1</version>
<configuration>
<source>1.8</source>
<target>1.8</target>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<version>3.0.0-M5</version>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-report-plugin</artifactId>
<version>3.0.0-M5</version>
</plugin>
</plugins>
</build>
</project>
Option B – Installing JUnit jar in Eclipse as External Jar
Apart from adding the JUnit and Hamcrest dependencies via the pom file, the other option is installing those jar files via ‘configuration of the build path’. In this case, the entries related to JUnit and Hamcrest jar files are not required in pom.xml.
To install the JUnit jar in Eclipse, right-click on the project and click on ‘Build Path’ ? ‘Configure Build Path’.
Go to ‘Java Build Path’ and click on the ‘Add External JARs’ button to add JUnit.jar and Hamcrest-2.2.jar to the project.
Since JUnit and Hamcrest jars are added as External Jars, pom.xml does not contain references for adding JUnit and Hamcrest jar.
This is how pom.xml looks like when this option is selected:
Shown below is the complete pom.xml:
<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 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.test</groupId>
<artifactId>junitdemo</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging>
<name>junitdemo</name>
<url>http://maven.apache.org</url>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>
<dependencies>
<dependency>
<groupId>org.seleniumhq.selenium</groupId>
<artifactId>selenium-java</artifactId>
<version>4.0.0-alpha-6</version>
</dependency>
<dependency>
<groupId>org.seleniumhq.selenium</groupId>
<artifactId>selenium-chrome-driver</artifactId>
<version>4.0.0-alpha-6</version>
</dependency>
<dependency>
<groupId>io.github.bonigarcia</groupId>
<artifactId>webdrivermanager</artifactId>
<version>4.1.0</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-nop</artifactId>
<version>1.7.28</version>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<!-- <defaultGoal>install</defaultGoal>-->
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.5.1</version>
<configuration>
<source>1.8</source>
<target>1.8</target>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<version>3.0.0-M5</version>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-report-plugin</artifactId>
<version>3.0.0-M5</version>
</plugin>
</plugins>
</build>
</project>
Once the JUnit and Hamcrest jars are added as ‘External Jars,’ you can see the same being reflected in the ‘Referenced Libraries’ section of the workspace.
Execution of JUnit tests in Eclipse
To execute the JUnit tests, right-click on the project and select ‘Run As’ ? ‘JUnit Test’.
As seen in the execution snapshot, the test was executed successfully on the cloud-based Selenium Grid on LambdaTest.
- The assertThrows method was added to the Assert class in JUnit 4.13. With this, you can assert that a certain function call results in a particular exception type being thrown.
- The try..catch idiom is a common way to raise asserts, especially if the code does not support lambdas.
- The @test annotation in combination with expected , the optional parameter, takes as values subclasses of Throwable. The expected parameter should be used with the utmost care, as the particular test will only pass if the expected exception is raised!
We did a minor modification in the example implementation where the newly added element does not match with the expected element. Here is the code snippet of the same:
package com.test.junitdemo;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.*;
..................
..................
..................
..................
@Test
public void test_LT_ToDoApp() throws InterruptedException {
driver.navigate().to(URL);
driver.manage().window().maximize();
..................
..................
..................
..................
try {
/* Let's mark done first two items in the list. */
driver.findElement(By.id("sampletodotext")).sendKeys("Happy Testing at LambdaTest");
driver.findElement(By.id("addbutton")).click();
/* Let's check that the item we added is added in the list. */
String enteredText = driver.findElement(By.xpath("/html/body/div/div/div/ul/li[6]/span")).getText();
Assert.assertEquals(enteredText, "LT - Happy Testing at LambdaTest");
..................
..................
..................
..................
As the newly added item does not match the expected one [i.e., LT -Happy Testing at LambdaTest], an assert is raised. Once the test is executed, the stacktrace is available in the window that shows details about the Test run (in JUnit).
Here is the snapshot of the window indicating that an assert is raised due to failure encountered in the test:
To copy the stack trace for further analysis, right-click on the test case (in the JUnit Runner window) and select ‘Copy Trace’. You can now copy the stack trace in some editor like Notepad++, Visual Studio Code, etc., for analyzing the problem. As seen in the stacktrace, the issue was encountered on line (117) where an assert is raised:
Alternatively, you can also select ‘Compare Result’ to check what should be the expected result.
Note- NoTestsRemainException happens when runner does not have any test to execute. Example, Running test of a group where not test match or using any filter which does not has any test to execute by runner.
Setting to setup Eclipse for using JUnit’s static imports
The Eclipse IDE adds import statements when you auto-complete a type, press the combination CTRL + SHIFT + O, or organize the imports when you save the project.
Here are the two ways for adding static imports when you use auto-complete:
Option 1
Go to Window ? Preferences ? Java ? Editor ? Content Assist. Enable the option Use static imports (only 1.5 or higher).
The next step is to tell Eclipse about the classes that you want to add as static imports. Here is how it can be done:
- Go to Window ? Preferences ? Java ? Editor ? Content Assist ? Favorites
- Click on New Type
- Enter the desired imports and click OK. There is an option to search for the desired Import and add the same. For example, if you want to add org.junit.Assert; Eclipse adds the entry org.junit.Assert.*
- For verifying whether the settings work, type assertEquals, press CTRL+Space, and press Enter. Depending on the Organize Imports preferences, Eclipse adds static import org.junit.Assert.assertEquals or org.junit.Assert.* to the code.
Option 2
The other way to add static JUnit imports is through the key combination CTRL + SHIFT + M (Source > Add Import), the same option used for adding missing imports. The refactoring adds static import for the defining class, along with removing the class dot expression.
For example, if the code contains the line org.junit.Assert.assertEquals(), simply place the cursor on org.junit.Assert.assertEquals() and press the key combination CTRL + SHIFT + M. It would add the line import static org.junit.Assert.assertEquals;
or org.junit.Assert
.* in the code.
This particular feature has been there for a long time and can be used as a quick hack for adding JUnit’s static imports in the code.
JUnit IDE Compatibility Dependencies
In the previous sections, we have covered the setup and installation of JUnit 4. We also looked at how we can use the Eclipse IDE with JUnit 4. As far as dependencies for JUnit 4 are concerned, JUnit 4 requires JDK (or Java) version 5 or above on the target machine.
To be able to execute JUnit 4 tests in Eclipse, we need the following dependencies:
</dependencies>
[...]
<dependency>
<groupId>hamcrest</groupId>
<artifactId>hamcrest</artifactId>
<version>2.2</version>
<scope>system</scope>
<systemPath>C:\JUnit\hamcrest-2.2.jar</systemPath>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.13.1</version>
<scope>system</scope>
<systemPath>C:\JUnit\junit.jar</systemPath>
</dependency>
[...]
</dependencies>
The above dependencies should be programmed in pom.xml. Here, we have added JUnit and Hamcrest as local dependencies. On the other hand, you can also download Maven dependencies in Eclipse by adding the dependency information in pom.xml
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.13.1</version>
</dependency>
We recommend checking Dependency Info on the JUnit website if you are looking for dependency information for other build dependency managers like Apache Ivy, Apache Buildr, etc.
How to use JUnit with IntelliJ IDEA IDE?
If you are looking for a good Eclipse alternative for writing JUnit tests, IntelliJ IDEA IDE should be on your list. IntelliJ IDEA IDE is a cross-platform IDE that is written in Java and Kotlin. It is developed by JetBrains and is available as an Apache-licensed community edition. It is also available in the proprietary commercial edition.
It is available for installation on Windows, Linux, and macOS. Apart from Java and Kotlin, the other JVM languages supported by IntelliJ IDEA IDE are Scala and Groovy. Plugins in IntelliJ IDE help in using the IDE with other programming languages like PHP, Python, Ruby, JavaScript, and more.
The community edition of IntelliJ IDEA IDE provides all the necessary features required for efficiently writing JUnit tests.
IntelliJ IDEA Environment
To get started with JUnit tests with IntelliJ IDE, perform the following steps:
- Create a new Maven project in IntelliJ. Select the project SDK. In our case, we have selected:
- Name the project as JUnitDemo, as we would be using the same files (i.e., JUnitDemo.java and pom.xml) from the Eclipse project.
- In case you have a number of Java SDK versions installed in the system, you can choose the appropriate Java SDK by Right-clicking on the project ? Open Module Settings ? Project item (under Project Settings)
In Project SDK, select the Java SDK of your choice. In our case, we have selected the Java version “15.0.1”. Click Ok to apply the settings.
- Once the project structure is ready, we create a new package in \src\test\java.
- We name the package as com.test.junitdemo.
- Right-click on the newly created package (i.e., com.test.junitdemo) and create a new ‘Java Class’.
- The Java class is named JUnitDemo.
- Copy the implementation of JUnitDemo.java to the JUnitDemo class file created under the com.test.junitdemo package. Copy the content of pom.xml, which we used in the Eclipse project in pom.xml of this project.
Since the pom.xml is updated, click on the ‘Maven’ Icon shown below for POM changes to affect the implementation.
Running JUnit with IntelliJ IDEA
This is similar to the step mentioned for setting up JUnit in the Eclipse workspace. The only difference is that now the IDE is IntelliJ IDEA instead of Eclipse. There are two ways for adding local dependencies (i.e., JUnit and Hamcrest) to a JUnit project in IntelliJ IDEA.
Option A – Setting up pom.xml (to add JUnit, Hamcrest, and other relevant dependencies)
The path to local dependencies (i.e., JUnit and Hamcrest) is mentioned in pom.xml. This means that the pom.xml, which was used in the JUnit configuration step in Eclipse, can be used without any modifications for IntelliJ IDEA.
Shown below is the location of JUnit 4.13.1 jar (i.e., juni.jar) and Hamcrest jar (i.e., hamcrest-2.2.jar)
Here is the snippet of pom.xml, which shows how the local dependencies are mentioned in the pom file:
</dependencies>
[...]
<dependency>
<groupId>hamcrest</groupId>
<artifactId>hamcrest</artifactId>
<version>2.2</version>
<scope>system</scope>
<systemPath>C:\JUnit\hamcrest-2.2.jar</systemPath>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.13.1</version>
<scope>system</scope>
<systemPath>C:\JUnit\junit.jar</systemPath>
</dependency>
[...]
</dependencies>
To verify whether the local dependencies are included due to the changes in pom.xml, double click on any JUnit import statement (e.g., import org.junit.AfterClass;) and you would be able to see if the local dependencies (for JUnit) are fulfilled due to pom.xml.
Option B – Installing JUnit jar in IntelliJ as External Jar
In case you do not want to add the local dependencies through pom.xml, the same can also be added through the GUI. Dependency is a library that is a collection of compiled code that the module depends on. In our case, the external libraries (or jar files) that have to be included are JUnit and Hamcrest.
In IntelliJ IDEA, libraries can be defined at three broad levels:
- Global – Available for many projects
- Module – Available for that particular module
- Project – Available for all modules within the project
In our case, we would install the external libraries (or dependencies) at the ‘Project Level’. Perform the steps mentioned below for adding JUnit and Hamcrest jars as external libraries:
- Right Click on the project (or Go to File ? Project Structure in the Menu) and go to ‘Open Module Settings’.
- In the current window, select Project Settings ? Libraries. To add the two jar files, click on the + button, and select Java.
- Go to the path that contains the JUnit and Hamcrest jar files. Select those files and click ‘OK’.
- You can see that the two jar files are added as ‘External Libraries’ to the project.
- To verify whether the External Libraries are added successfully, double click on any JUnit import statement (e.g., import org.junit.AfterClass ). You will see that it refers to the JUnit jar, which is included as an External Library in the project.
Execution of JUnit tests in IntelliJ IDEA
For running JUnit tests in IntelliJ IDEA, right-click on the project and click on ‘Run All Tests’.
You can also run JUnit tests by right-clicking on a particular test (e.g., JUnitDemo) and clicking on ‘Run TestName’ (e.g., Run JUnitDemo).
As seen in the execution snapshot, the test was executed successfully on the cloud-based Selenium Grid on LambdaTest.
That’s All Folks
JUnit is one of the popular open-source test frameworks used for unit testing with Java. When using JUnit, you can add the dependencies dynamically using Maven or adding the respective dependencies as ‘local dependencies’ (or External Libraries).
For testing with the JUnit framework, you can use Eclipse or IntelliJ IDEA – the most popular IDEs for JUnit testing. I personally prefer IntelliJ IDE since I find it more developer-friendly in comparison to Eclipse IDE. JUnit can be used with a local Selenium Grid as well as a cloud-based Selenium Grid like LambdaTest.
Posted on January 29, 2021
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.
Related
September 21, 2023