Sub topic 1
Why Write Unit Tests?
What a Unit Test Is
A unit test is a small piece of code that checks one small piece of your program, such as one method. It runs the method, then checks that the result is what you expect.
You could check your code by hand. Unit tests matter because they are automated, which means the computer runs them for you. Each test runs in milliseconds, and you can run it again after every change. If a change breaks something that used to work, a test fails and tells you right away. That kind of bug is called a regression.
JUnit 5 is the most widely used testing framework for Java. A framework is a library that gives you ready-made tools. JUnit gives you tools to write tests and run them.
Setting Up JUnit 5
A dependency is a library your project downloads and uses. In Maven, add this inside <dependencies> in pom.xml:
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter</artifactId>
<version>5.11.3</version>
<scope>test</scope>
</dependency>The test scope keeps JUnit out of your finished program. If you use Gradle with the Kotlin build file build.gradle.kts, add this instead:
dependencies {
testImplementation(platform("org.junit:junit-bom:5.11.3"))
testImplementation("org.junit.jupiter:junit-jupiter")
testRuntimeOnly("org.junit.platform:junit-platform-launcher")
}
tasks.test {
useJUnitPlatform()
}Your First Test
Here is the code to test. Put it in src/main/java/Calculator.java:
public class Calculator {
public int add(int a, int b) {
return a + b;
}
}Put the test in src/test/java/CalculatorTest.java:
import static org.junit.jupiter.api.Assertions.assertEquals;
import org.junit.jupiter.api.Test;
class CalculatorTest {
@Test
void addReturnsSum() {
Calculator calculator = new Calculator();
int result = calculator.add(2, 3);
assertEquals(5, result);
}
}@Test is an annotation, a label that tells JUnit "this method is a test." assertEquals(expected, actual) passes when the two values match. When they don't match, the test fails.
Running Tests and Reading Results
In your IDE, click the green arrow next to the test method. From the command line, run mvn test for Maven or ./gradlew test for Gradle.
A passing test shows green. A failing test shows red, along with a message like expected: <5> but was: <6>. That message tells you what you expected and what the code actually returned.
Exercise
You change add to return a - b and run mvn test. What happens, and what does the message say?
Show answer
The test fails and shows red. The message says expected: <5> but was: <-1>, because 2 - 3 is -1.