下面用由浅入深的方式,告诉你如何用 Java + JUnit 写测试(以 JUnit 5 为主,目前最常用)。
在 pom.xml 中加入:
<dependencies>
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter</artifactId>
<version>5.10.0</version>
<scope>test</scope>
</dependency>
</dependencies>
src
├── main
│ └── java
│ └── com.example.Calculator
└── test
└── java
└── com.example.CalculatorTest
public class Calculator {
public int add(int a, int b) {
return a + b;
}
}
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.*;
class CalculatorTest {
@Test
void testAdd() {
Calculator calculator = new Calculator();
int result = calculator.add(2, 3);
assertEquals(5, result);
}
}
✅ 运行方式:
mvn testassertEquals(expected, actual);
assertNotEquals(a, b);
assertTrue(condition);
assertFalse(condition);
assertNull(obj);
assertNotNull(obj);
assertThrows(Exception.class, () -> method());
assertArrayEquals(new int[]{1,2}, arr);
import org.junit.jupiter.api.*;
class LifecycleTest {
@BeforeAll
static void initAll() {
System.out.println("所有测试前执行一次");
}
@BeforeEach
void init() {
System.out.println("每个测试前执行");
}
@Test
void test1() {}
@Test
void test2() {}
@AfterEach
void tearDown() {}
@AfterAll
static void tearDownAll() {}
}
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.ValueSource;
class ParamTest {
@ParameterizedTest
@ValueSource(ints = {1, 2, 3})
void testWithParams(int num) {
assertTrue(num > 0);
}
}
@Test
void testException() {
assertThrows(IllegalArgumentException.class, () -> {
throw new IllegalArgumentException("error");
});
}
通常配合 Mockito 使用:
@Test
void testService() {
UserRepository repo = mock(UserRepository.class);
when(repo.findName(1)).thenReturn("Tom");
UserService service = new UserService(repo);
assertEquals("Tom", service.getName(1));
}
| 功能 | JUnit 4 | JUnit 5 |
|---|---|---|
| 测试注解 | @Test |
@Test |
| 前置 | @Before |
@BeforeEach |
| 全局前置 | @BeforeClass |
@BeforeAll |
| 断言 | Assert.assertEquals |
Assertions.assertEquals |
shouldReturnXWhenY如果你愿意,可以告诉我:
我可以直接给你对应场景的完整示例。
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。