How to Setup JUnit and Write Your First Test

:question: Need help setting up your Java testing environment?

:eyes: Watch this video to learn how to get started with JUnit, install JDK & IntelliJ, and configure Maven for seamless testing! :rocket:

Hey @kavitajoshi,

Thank you for sharing this video—it’s really insightful! :raised_hands:
That said, I found the installation even easier to follow with the steps below:

:white_check_mark: Using Maven (most popular & scalable) Add the following to your pom.xml:

<dependency>
  <groupId>junit</groupId>
  <artifactId>junit</artifactId>
  <version>4.13.2</version>
  <scope>test</scope>
</dependency>

Once that’s in place, Maven will automatically pull in JUnit.
Just create your test class, use the @Test annotation, and you’re good to go!

This setup is super helpful if you’re planning to integrate with CI tools or scale your test suite—perfect for real-world JUnit environment setups. :ok_hand:

I usually make use of Gradle as its lightweight & flexible.

Add JUnit to your build.gradle:

testImplementation 'junit:junit:4.13.2'

Gradle will take care of fetching the dependency. You can then create your test class and use ./gradlew test to run them. If you’re newer to Gradle, don’t worry—it makes managing dependencies super painless. Another clean option for a junit environment that doesn’t feel heavy.

Thanks for sharing your insights @richaaroy & @dimplesaini.230! :raised_hands: I’d also like to add the manual process, which might feel a bit traditional—but honestly, it’s a solid way to learn the ropes.


Manual Setup (if you’re not using a build tool yet)

  1. Download the required JARs:
  • junit-4.13.2.jar
  • hamcrest-core.jar
  1. Add both to your project’s classpath.
  2. Create a test class like this:
import org.junit.Test;
import static org.junit.Assert.*;

public class MyTest {
  @Test
  public void testSomething() {
    assertEquals(4, 2 + 2);
  }
}

This approach is perfect if you’re just getting started and haven’t set up Maven or Gradle yet. It’s a great way to build a strong foundation in the JUnit environment before moving into more automated workflows. :rocket: