Skip to content

Yet another programming solutions log

Sample bits from programming for the future generations.

Technologies Technologies
  • Algorithms and Data Structures
  • Java Tutorials
  • JUnit Tutorial
  • MongoDB Tutorial
  • Quartz Scheduler Tutorial
  • Spock Framework Tutorial
  • Spring Framework
  • Bash Tutorial
  • Clojure Tutorial
  • Design Patterns
  • Developer’s Tools
  • Productivity
  • About
Expand Search Form

JUnit Getting Started

farenda 2015-12-23 0

How start with JUnit, setup and write basic test? In this post we’ll show how to start with the most popular unit testing library in 5 minutes! Let’s test!

Setup in Maven 3

Add junit:junit dependency with scope test to the project configuration and Maven will pick it up automatically. What more Maven will also run its Surefire plugin to run JUnit tests found in default src/test/java directory.

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="https://maven.apache.org/POM/4.0.0" xmlns:xsi="https://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="https://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.farenda.tutorials</groupId>
    <artifactId>junit</artifactId>
    <version>0.0.1-SNAPSHOT</version>

    <properties>
        <java.version>1.8</java.version>
    </properties>

    <!-- the important part: -->
    <dependencies>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <!-- use the latest version: -->
            <version>4.12</version>
            <!-- we want it only for tests: -->
            <scope>test</scope>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>3.1</version>
                <configuration>
                    <source>${java.version}</source>
                    <target>${java.version}</target>
                </configuration>
            </plugin>
        </plugins>
    </build>

</project>

Setup in Gradle

Gradle configuration is very similar – build.gradle:

apply plugin: 'java'

jar {
    baseName = 'junit'
    version =  '0.1.0'
}

repositories {
    mavenCentral()
}

sourceCompatibility = 1.8
targetCompatibility = 1.8

dependencies {
    testCompile group:'junit', name:'junit', version:4.12
}

Basic test

Let’s suppose that we would like to test the following class, located in src/main/java/com/farenda/junit:

package com.farenda.junit;

public class User {

    private final String firstName;
    private final String lastName;

    public User(String firstName, String lastName) {
        this.firstName = firstName;
        this.lastName = lastName;
    }

    public String getFirstName() {
        return firstName;
    }

    public String getLastName() {
        return firstName;
    }
}

To do that we can write the following JUnit test and put it in src/test/java/com/farenda/junit. Maven and Gradle will automatically pick up from this location classes ending with Test.

package com.farenda.junit;

import org.junit.Test;

import static org.junit.Assert.assertEquals;

public class UserTest {

    @Test
    public void userShouldHaveGivenName() {
        User user = new User("Michael", "Jordan");

        assertEquals("Michael", user.getFirstName());
        assertEquals("Jordan", user.getLastName());
    }
}

Every test have to be annotated with @Test annotation to let JUnit know that it is a test. To verify results JUnit provides Assert class, which contains many static helper methods. The most common one is assertEquals, which we use here – it takes two arguments, compares them and throws an exception when they are not equal.

The above code has one bug which will be reported by JUnit as here:

org.junit.ComparisonFailure:
Expected :Jordan
Actual   :Michael

at org.junit.Assert.assertEquals(Assert.java:115)
at org.junit.Assert.assertEquals(Assert.java:144)
at com.farenda.junit.UserTest.userShouldHaveGivenName(UserTest.java:14)

How Pros do it

The following code is part of TriStateTest.java from Facebook Fresco project:

package com.facebook.common.util;

import org.junit.Test;

import static org.junit.Assert.*;

/** Unit test for {@link TriState}. */
public class TriStateTest {

  //... other tests commented out for brevity

  @Test
  public void testValueOf() {
    assertEquals(TriState.YES, TriState.valueOf(true));
    assertEquals(TriState.NO, TriState.valueOf(false));
  }

  //... other tests commented out for brevity
}

Have other interesting examples? Let us know in the comments! :-)

Share with the World!
Categories JUnit Tags java, junit, unit-tests
Previous: Java Console read password
Next: JUnit Assert CheatSheet

Recent Posts

  • Java 8 Date Time concepts
  • Maven dependency to local JAR
  • Caesar cipher in Java
  • Java casting trick
  • Java 8 flatMap practical example
  • Linked List – remove element
  • Linked List – insert element at position
  • Linked List add element at the end
  • Create Java Streams
  • Floyd Cycle detection in Java

Pages

  • About Farenda
  • Algorithms and Data Structures
  • Bash Tutorial
  • Bean Validation Tutorial
  • Clojure Tutorial
  • Design Patterns
  • Java 8 Streams and Lambda Expressions Tutorial
  • Java Basics Tutorial
  • Java Collections Tutorial
  • Java Concurrency Tutorial
  • Java IO Tutorial
  • Java Tutorials
  • Java Util Tutorial
  • Java XML Tutorial
  • JUnit Tutorial
  • MongoDB Tutorial
  • Quartz Scheduler Tutorial
  • Software Developer’s Tools
  • Spock Framework Tutorial
  • Spring Framework

Tags

algorithms bash bean-validation books clojure design-patterns embedmongo exercises git gof gradle groovy hateoas hsqldb i18n java java-basics java-collections java-concurrency java-io java-lang java-time java-util java-xml java8 java8-files junit linux lists log4j logging maven mongodb performance quartz refactoring regex rest slf4j solid spring spring-boot spring-core sql unit-tests

Yet another programming solutions log © 2021

sponsored