In this chapter, we will guide you through setting up your environment for using JUnit. We will cover the steps to install JUnit, integrate it with your development environment, and create a simple JUnit test to verify that everything is set up correctly.
Installing JUnit
JUnit can be added to your project as a dependency. Here, we will cover the steps for Maven and Gradle.
Using Maven
To use JUnit with Maven, you need to add the JUnit dependency to your pom.xml file:
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter-engine</artifactId>
<version>5.8.2</version>
<scope>test</scope>
</dependency>
Using Gradle
To use JUnit with Gradle, you need to add the JUnit dependency to your build.gradle file:
dependencies {
testImplementation 'org.junit.jupiter:junit-jupiter-engine:5.8.2'
}
Setting Up JUnit in IDEs
Eclipse
- Install JUnit Plugin: Most modern versions of Eclipse come with JUnit pre-installed. To check, go to
Help>Eclipse Marketplaceand search for JUnit. - Create a New Java Project: Go to
File>New>Java Project. - Add JUnit Library: Right-click on your project, go to
Build Path>Add Libraries, and selectJUnit.
IntelliJ IDEA
- Create a New Java Project: Go to
File>New>Project. - Add JUnit Library: Open the
Project Structuredialog (File>Project Structure), go toLibraries, and add a new library by searching for JUnit.
VS Code
- Install Java Extension Pack: Install the Java Extension Pack from the Visual Studio Code Marketplace.
- Create a New Java Project: Use the Java Extension Pack to create a new Java project.
- Add JUnit Dependency: Add the JUnit dependency to your
build.gradleorpom.xmlfile as shown above.
Writing Your First JUnit Test
Let’s create a simple Java class and write a test for it to make sure everything is set up correctly.
Example Java Class
public class Calculator {
public int add(int a, int b) {
return a + b;
}
}
Example JUnit Test
Create a new test class for the Calculator class.
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertEquals;
public class CalculatorTest {
@Test
public void testAdd() {
Calculator calculator = new Calculator();
int result = calculator.add(2, 3);
assertEquals(5, result, "2 + 3 should equal 5");
}
}
Running the JUnit Test
Using Eclipse
- Run Test: Right-click on the test file or test method and select
Run As>JUnit Test.
Using IntelliJ IDEA
- Run Test: Click the green run icon next to the test method or class and select
Run.
Using VS Code
- Run Test: Open the test file and click the
Runicon above the test method.
Conclusion
You have now set up JUnit in your development environment and written a simple test to ensure everything is working correctly. This setup will enable you to start writing and running tests for your Java applications.