Skip to content
Tutorials Center
My learning

Topics

Lesson 2 of 29 ยท Getting started

Your First JUnit Test

Write and run your first JUnit 6 test: the @Test annotation, arrange-act-assert, project layout, naming, and how to read a green or red test report.

A JUnit test is an ordinary Java method that calls your code and checks the answer. If the method finishes quietly, the test passes. If it throws, the test fails. That is the whole idea, and everything else in this track (lifecycles, parameters, extensions) is built on top of it. In this lesson you will write real JUnit 6 tests, run them, and learn to read what comes back.

Unlike most lessons about big frameworks, this one is fully runnable. Our Java runner has the JUnit Platform on its classpath, so every example below uses the real org.junit.jupiter annotations and assertions. The only thing we replace is the launcher glue: in a real project Maven, Gradle or your IDE finds and runs your tests; here a short helper at the bottom of each file does the same job.

If you have never written a test before, Unit Testing in Java is a gentler warm-up. This lesson assumes you can read a Java class. For a second angle on the same material, see Unit Testing with JUnit 6 in the Advanced Java course.

The anatomy of a test class

A test is a method with a job

@Test Marks a method as a test.
Call The test calls the code under test.
Assert A failed assertion throws and fails the test.

No exception means the test passed.

1 / 3

A minimal test class looks like this:

Java
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertEquals;

class GreeterTest {

    @Test
    void greetsByName() {
        Greeter greeter = new Greeter();           // arrange

        String message = greeter.greet("Ada");     // act

        assertEquals("Hello, Ada!", message);      // assert
    }
}

Four details matter here:

  • @Test comes from org.junit.jupiter.api. In JUnit 4 the same annotation lived in org.junit, and mixing them up is the number one reason "my test does not run". Jupiter is the programming model you use with JUnit 6 (see Testing landscape for how the pieces fit).
  • The class and methods can be package-private. JUnit 4 forced you to write public; Jupiter does not. A test method must not be private or static, and it must return void.
  • Assertions is a bag of static methods. import static org.junit.jupiter.api.Assertions.*; is the usual way to use them without the class prefix. The next lessons cover them all; here we need only assertEquals, assertTrue and assertFalse.
  • The expected value goes first. assertEquals(expected, actual). Swapping them does not change pass or fail, but it reverses the failure message and sends the next reader in the wrong direction.

Running your first tests

The class under test below checks whether a password is acceptable. It is small on purpose: the point is the shape of the tests. Everything sits inside one file so the runner can reach it, and the tests are public static nested classes only because of that. In a real project the production class and the test class live in separate files (more on that in a moment).

Java Four passing tests

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

Press Run and you will see a tree: the test class name, then one [PASS] line per method, then a summary line. That summary is what a build server cares about: any failed test turns the whole build red.

Notice the test names. They are sentences that describe behavior, so a failing line such as rejectsPasswordsWithoutDigits tells you what broke before you open any code. Compare that with test3, which tells you nothing.

Red, green and what failure looks like

A test suite that has never failed proves nothing, because you cannot tell a test that works from one that checks nothing. Always make a new test fail once, on purpose, before you trust it. Below is a deliberately buggy average method with three tests. Run it before you read the explanation.

Java Two failures and one pass

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

You get exactly one pass and two different kinds of problem:

  • averageKeepsTheFraction fails with AssertionFailedError: expected: <1.5> but was: <1.0>. The code ran to completion and returned a wrong answer. The fix is (double) sum / values.length.
  • averageOfNothingIsNotDefined errors with ArithmeticException: / by zero. The code crashed before any comparison happened. Here the test is wrong as much as the code: the right fix is to decide what an empty array should do (throw IllegalArgumentException, say) and assert that, which is the topic of JUnit Assertions in Depth.

JUnit's report calls both outcomes "failed", but the exception class tells you which story you are in. An AssertionFailedError means "wrong value"; anything else means "unexpected crash". Reading the exception name first saves minutes of debugging.

Fix the division, change the empty-array test so it expects an exception (or delete it for now), run again, and enjoy the all-green tree. That loop (see red, change, see green) is the engine of test-driven development, which you will practice in the bank account project later in this track.

Project layout and naming

Real projects separate production code from tests. Maven and Gradle both use the same convention, so you will see it everywhere:

TEXT
my-app/
  pom.xml                      (or build.gradle.kts)
  src/
    main/java/com/shop/Discounts.java
    test/java/com/shop/DiscountsTest.java

Rules of thumb:

  • Mirror the package. com.shop.DiscountsTest sits in the same package as com.shop.Discounts, so tests can use package-private members without making them public just for testing.
  • Name the class after what it tests, with a Test suffix: DiscountsTest. Maven's Surefire plugin looks for names like *Test, Test* and *Tests by default, and a class called DiscountChecks would be silently ignored by mvn test. That surprise is common enough that it is worth remembering now.
  • One test class per production class is a good starting point; split later if a test class grows past a few hundred lines.
  • Test code is code. Keep it as readable as production code, because you will read it when something breaks.

To run tests in a real project you do not call any Launcher yourself. You press the green arrow next to the class in IntelliJ IDEA, Eclipse or VS Code, or you run a build command (read-only, shown for reference):

Terminal
mvn test            # Maven, runs every test class Surefire can find
gradle test         # Gradle
mvn test -Dtest=DiscountsTest   # one class

Under the hood, all of these hand your classes to the JUnit Platform launcher, which asks the Jupiter engine to discover and run them. The run(...) helper in our examples calls that same launcher directly, so what you see in the console is a faithful miniature of a real run. The Running Tests with Maven and Gradle lesson covers the build side in depth.

Common beginner mistakes

  • Wrong import. org.junit.Test (JUnit 4) on a method in a Jupiter project: the test compiles and is then ignored, or fails to be found. Import from org.junit.jupiter.api.
  • A test with no assertion. It passes whenever the code does not throw, which is rarely what you meant. Every test should end by checking something.
  • Testing the framework instead of your code. assertEquals(5, 5) always passes. Compare your code's output with a value you computed by hand.
  • Printing instead of asserting. System.out.println(result) needs a person to read it every time. An assertion checks it on every build.
  • Depending on test order. JUnit does not promise one. Each test must set up what it needs.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. When does a JUnit test pass?

    A test passes if the method completes. Assertions throw AssertionFailedError when they fail, and any thrown exception fails the test.
  2. 2. Which method signature will JUnit Jupiter run as a test?

    Test methods must be non-private, non-static and return void. Package-private is fine and is the usual style in Jupiter.
  3. 3. The report shows ArithmeticException: / by zero for a test. What does that tell you?

    Only a mismatched assertion produces an AssertionFailedError. Any other exception means execution blew up before a comparison was made.
  4. 4. In which folder does test code normally live in a Maven or Gradle project?

    Both build tools compile src/test/java separately and add the test libraries only there. Using the same package gives tests access to package-private members.
  5. 5. Why should you make a new test fail once before trusting it?

    A test that cannot fail gives false confidence. Seeing it go red against broken code shows that its assertions really check something.

Summary

  • A JUnit test is a void, non-private, non-static method marked @Test; it passes unless it throws.
  • Shape tests as arrange, act, assert, with the expected value first in assertEquals(expected, actual).
  • AssertionFailedError means a wrong value; any other exception means the code crashed.
  • Put tests in src/test/java in the same package as the class under test, and name classes *Test so Surefire finds them.
  • On this site the JUnit 6 API is real; the run(...) helper only replaces what Maven, Gradle or your IDE does for you.
  • Make every new test fail once, on purpose, before you rely on it.

Next: Your First TestNG Test, the other major Java testing framework, side by side with what you just learned.