Junit简单使用

1. 添加junit依赖

在springboot-boot-starter-test中已经包含了此依赖, 可以不用添加

<dependency>
    <groupId>org.junit.jupiter</groupId>
    <artifactId>junit-jupiter</artifactId>
    <version>5.10.0</version>
    <scope>test</scope>
</dependency>

 

2. 编写测试类

创建一个测试类,通常以 Test 结尾。例如:

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

class MyServiceTest {

    @Test
    void testAddition() {
        int result = 2 + 3;
        assertEquals(5, result, "2 + 3 应该等于 5");
    }
}

 

3. 常用注解:

@Test: 标记方法为测试方法。

@BeforeEach: 在每个测试方法运行前执行。

@AfterEach: 在每个测试方法运行后执行。

@BeforeAll: 在所有测试方法运行前执行(静态方法)。

@AfterAll: 在所有测试方法运行后执行(静态方法)。

实例:

import org.junit.jupiter.api.*;

class LifecycleTest {

    @BeforeAll
    static void beforeAll() {
        System.out.println("在所有测试方法之前运行");
    }

    @BeforeEach
    void beforeEach() {
        System.out.println("在每个测试方法之前运行");
    }

    @Test
    void testExample1() {
        System.out.println("执行测试方法1");
        assertTrue(true);
    }

    @Test
    void testExample2() {
        System.out.println("执行测试方法2");
        assertNotNull("JUnit");
    }

    @AfterEach
    void afterEach() {
        System.out.println("在每个测试方法之后运行");
    }

    @AfterAll
    static void afterAll() {
        System.out.println("在所有测试方法之后运行");
    }
}

 

4. 运行测试

在 IDE(如 IntelliJ IDEA 或 Eclipse)中右键点击测试类或方法,选择“Run”。

使用 Maven 执行测试:

mvn test

 

5. 测试结果断言

JUnit 提供了多种断言方法来验证测试结果:

assertEquals(expected, actual): 验证两个值相等。

assertTrue(condition): 验证条件为真。

assertFalse(condition): 验证条件为假。

assertNotNull(object): 验证对象不为空。

assertThrows(exceptionClass, executable): 验证抛出指定异常。

实例:

@Test
void testAssertions() {
    assertEquals(5, 2 + 3);
    assertTrue(3 > 1);
    assertFalse(2 < 1);
    assertNotNull("JUnit");
    assertThrows(ArithmeticException.class, () -> {
        int result = 1 / 0;
    });
}
暂无评论

发送评论 编辑评论


				
|´・ω・)ノ
ヾ(≧∇≦*)ゝ
(☆ω☆)
(╯‵□′)╯︵┴─┴
 ̄﹃ ̄
(/ω\)
∠( ᐛ 」∠)_
(๑•̀ㅁ•́ฅ)
→_→
୧(๑•̀⌄•́๑)૭
٩(ˊᗜˋ*)و
(ノ°ο°)ノ
(´இ皿இ`)
⌇●﹏●⌇
(ฅ´ω`ฅ)
(╯°A°)╯︵○○○
φ( ̄∇ ̄o)
ヾ(´・ ・`。)ノ"
( ง ᵒ̌皿ᵒ̌)ง⁼³₌₃
(ó﹏ò。)
Σ(っ °Д °;)っ
( ,,´・ω・)ノ"(´っω・`。)
╮(╯▽╰)╭
o(*////▽////*)q
>﹏<
( ๑´•ω•) "(ㆆᴗㆆ)
😂
😀
😅
😊
🙂
🙃
😌
😍
😘
😜
😝
😏
😒
🙄
😳
😡
😔
😫
😱
😭
💩
👻
🙌
🖕
👍
👫
👬
👭
🌚
🌝
🙈
💊
😶
🙏
🍦
🍉
😣
Source: github.com/k4yt3x/flowerhd
颜文字
Emoji
小恐龙
花!
上一篇
下一篇