junit Installation or Setup


Example

Since JUnit is a Java library, all you have to do to install it is to add a few JAR files into the classpath of your Java project and you're ready to go.

You can download these two JAR files manually: junit.jar & hamcrest-core.jar.

If you're using Maven, you can simply add in a dependency into your pom.xml:

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

Or if you're using Gradle,add in a dependency into your build.gradle:

apply plugin: 'java'

dependencies {
    testCompile 'junit:junit:4.12'
}

After this you can create your first test class:

import static org.junit.Assert.assertEquals;

import org.junit.Test;

public class MyTest {
    @Test
    public void onePlusOneShouldBeTwo() {
        int sum = 1 + 1;
        assertEquals(2, sum);
    }
}

and run it from command line:

  • Windows java -cp .;junit-X.YY.jar;hamcrest-core-X.Y.jar org.junit.runner.JUnitCore MyTest
  • Linux or OsX java -cp .:junit-X.YY.jar:hamcrest-core-X.Y.jar org.junit.runner.JUnitCore MyTest

or with Maven: mvn test