Search⌘ K
AI Features

Our First Passing Test

Explore how to write your first passing unit test for a Java class using JUnit. Learn about the ScoreCollection class and how JUnit executes tests from top to bottom, passing tests if no assertions fail. This lesson helps you grasp foundational concepts of test execution and basic test writing in JUnit.

We'll cover the following...

For our first example, we’ll write tests against a small class named ScoreCollection. Its goal is to return the mean (average) for a collection of scoreable objects (things that answer with a score).

Now, let’s run the test below:

Java
package iloveyouboss;
@FunctionalInterface
public interface Scoreable {
int getScore();
}
Java
package iloveyouboss;
import java.util.*;
public class ScoreCollection {
private List<Scoreable> scores = new ArrayList<>();
public void add(Scoreable scoreable) {
scores.add(scoreable);
}
public int arithmeticMean() {
int total = scores.stream().mapToInt(Scoreable::getScore).sum();
return total / scores.size();
}
}

A ScoreCollection class accepts a Scoreable instance through its add() method. A Scoreable object is simply one that can return an int score value. Now Run the test below:

package iloveyouboss;
import static org.junit.Assert.*;
import org.junit.*;

public class ScoreCollectionTest {

	@Test
	public void test() {
	}
}
ScoreCollectionTest.java

The result Ok (1 test) in the output terminal shows that we have a passing test. Hurray!

Important design feature

The passing test clarifies two critical design features of JUnit:

  • When JUnit calls a test method, it executes statements top-to-bottom.
  • If JUnit runs through to the end of the test method without encountering an explicit fail (or an assertion that fails), the test passes.

Since our test statement is empty, it will always hit the end immediately and thus pass.