← Java OOP Knowledge Map← Java OOP 知识地图
JUnit Testing

JUnit Testing

JUnit is a Java unit testing framework. Small tests protect small methods and make refactoring safer.JUnit 是 Java 的单元测试框架。它的核心价值是:用小测试保护小方法,重构时知道自己有没有改坏行为。

Basic JUnit Shape

What a test looks like一个测试长什么样

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

class CircleTest {
    @Test
    void areaUsesRadiusSquared() {
        Circle c = new Circle(0, 0, 2);
        assertEquals(12.56, c.area(), 0.01);
    }
}
Arrange / Act / Assert

The three-step test shape写测试的三步

@Test
void depositAddsMoney() {
    BankAccount account = new BankAccount(100);
    account.deposit(50);
    assertEquals(150, account.getBalance());
}

Read it as: given this setup, when this action happens, then this result should hold.这个结构读起来像一句话:给定什么,执行什么,应该得到什么。