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:
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() {
}
}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.