JUnit Testing
JUnit is a Java unit testing framework. Small tests protect small methods and make refactoring safer.JUnit 是 Java 的单元测试框架。它的核心价值是:用小测试保护小方法,重构时知道自己有没有改坏行为。
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);
}
}
- test case: the Java class containing tests.:包含测试方法的 Java class。
- test method: a method annotated with
@Test.:带@Test的方法。 - assert: compares expected and actual values.:比较 expected 和 actual。
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.这个结构读起来像一句话:给定什么,执行什么,应该得到什么。