目錄
Set up JUnit in your project
Write a simple unit test with JUnit 5
Use setup and teardown with annotations
Best practices for writing good unit tests
Use mocking for dependencies
首頁 Java java教程 如何在Java編寫單元測試?

如何在Java編寫單元測試?

Aug 14, 2025 pm 07:28 PM
java 單元測試

要編寫Java單元測試,首先需在項目中引入JUnit 5,Maven項目在pom.xml中添加junit-jupiter依賴,Gradle項目添加testImplementation 'org.junit.jupiter:junit-jupiter:5.9.3',並將測試類置於src/test/java目錄下;接著創建測試類,使用@Test註解標記測試方法,通過assertEquals、assertThrows等斷言驗證行為,如測試Calculator類的add和divide方法;利用@BeforeEach和@AfterEach註解進行測試前準備和清理;遵循每次測試單一行為、使用描述性命名如shouldReturnSumWhenAddingTwoNumbers、採用AAA(Arrange-Act-Assert)結構組織測試代碼、覆蓋邊界條件如除零異常、保持測試獨立快速、通過Mockito模擬外部依賴如EmailService以隔離邏輯,最終實現可維護、可靠的單元測試體系。

How to write unit tests in Java?

Writing unit tests in Java is a fundamental practice for ensuring code correctness and maintainability. The most commonly used framework for this is JUnit , currently in its JUnit 5 version. Here's how to get started and write effective unit tests.


Set up JUnit in your project

Before writing tests, make sure JUnit is included in your project dependencies.

If you're using Maven , add this to your pom.xml :

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

For Gradle , include:

 testImplementation &#39;org.junit.jupiter:junit-jupiter:5.9.3&#39;

Tests are typically placed in the src/test/java directory, mirroring your main package structure.


Write a simple unit test with JUnit 5

Suppose you have a simple class:

 public class Calculator {
    public int add(int a, int b) {
        return ab;
    }

    public int divide(int a, int b) {
        if (b == 0) throw new IllegalArgumentException("Division by zero");
        return a / b;
    }
}

Here's how to test it:

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

public class CalculatorTest {

    private Calculator calculator = new Calculator();

    @Test
    public void testAdd() {
        int result = calculator.add(2, 3);
        assertEquals(5, result, "2 3 should equal 5");
    }

    @Test
    public void testDivide() {
        int result = calculator.divide(10, 2);
        assertEquals(5, result);
    }

    @Test
    public void testDivideByZero() {
        assertThrows(IllegalArgumentException.class, () -> {
            calculator.divide(10, 0);
        });
    }
}

Key points:

  • Use @Test to mark a method as a test.
  • assertEquals(expected, actual) checks if values match.
  • assertThrows verifies that an exception is thrown.

Use setup and teardown with annotations

If you need to prepare resources before or after tests:

 import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.AfterEach;

public class CalculatorTest {

    private Calculator calculator;

    @BeforeEach
    void setUp() {
        calculator = new Calculator();
    }

    @AfterEach
    void tearDown() {
        // Clean up if needed
    }

    @Test
    void testAdd() {
        assertEquals(4, calculator.add(1, 3));
    }
}

@BeforeEach runs before each test; @AfterEach runs after.


Best practices for writing good unit tests

  • Test one thing at a time
    Each test should verify a single behavior or edge case.

  • Use descriptive test names
    Instead of test1() , use shouldReturnSumWhenAddingTwoNumbers() .

    Example:

     @Test
    void shouldThrowExceptionWhenDividingByZero() {
        assertThrows(IllegalArgumentException.class, () -> {
            calculator.divide(5, 0);
        });
    }
  • Follow the AAA pattern
    Arrange, Act, Assert:

     @Test
    void addShouldReturnSumOfTwoNumbers() {
        // Arrange
        int a = 5;
        int b = 7;
        // Act
        int result = calculator.add(a, b);
        // Assert
        assertEquals(12, result);
    }
  • Test edge cases
    Include zero, negative numbers, null inputs, or invalid states.

  • Keep tests independent and fast
    Avoid dependencies between tests. Unit tests should run quickly and not rely on external systems like databases or networks.


Use mocking for dependencies

When your class depends on other components (eg, services, repositories), use Mockito to simulate them.

Add Mockito to your project:

 <dependency>
    <groupId>org.mockito</groupId>
    <artifactId>mockito-core</artifactId>
    <version>5.2.0</version>
    <scope>test</scope>
</dependency>

Example:

 import static org.mockito.Mockito.*;
import org.mockito.Mock;
import org.junit.jupiter.api.BeforeEach;

public class PaymentServiceTest {

    @Mock
    private EmailService emailService;

    private PaymentService paymentService;

    @BeforeEach
    void setUp() {
        MockitoAnnotations.openMocks(this);
        paymentService = new PaymentService(emailService);
    }

    @Test
    void processPaymentShouldSendEmailOnSuccess() {
        paymentService.processPayment(100.0);

        verify(emailService, times(1)).sendConfirmationEmail(100.0);
    }
}

This way, you isolate the logic of PaymentService without actually sending emails.


Basically, writing unit tests in Java involves setting up JUnit, writing focused test methods using assertions, organizing test lifecycle, and isolating dependencies with mocks when needed. It's not complicated, but consistency and good habits make a big difference.

以上是如何在Java編寫單元測試?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn

熱AI工具

Undress AI Tool

Undress AI Tool

免費脫衣圖片

Undresser.AI Undress

Undresser.AI Undress

人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover

AI Clothes Remover

用於從照片中去除衣服的線上人工智慧工具。

Clothoff.io

Clothoff.io

AI脫衣器

Video Face Swap

Video Face Swap

使用我們完全免費的人工智慧換臉工具,輕鬆在任何影片中換臉!

熱工具

記事本++7.3.1

記事本++7.3.1

好用且免費的程式碼編輯器

SublimeText3漢化版

SublimeText3漢化版

中文版,非常好用

禪工作室 13.0.1

禪工作室 13.0.1

強大的PHP整合開發環境

Dreamweaver CS6

Dreamweaver CS6

視覺化網頁開發工具

SublimeText3 Mac版

SublimeText3 Mac版

神級程式碼編輯軟體(SublimeText3)

熱門話題

PHP教程
1596
276
您目前尚未使用附上的顯示器[固定] 您目前尚未使用附上的顯示器[固定] Aug 19, 2025 am 12:12 AM

Ifyousee"YouarenotusingadisplayattachedtoanNVIDIAGPU,"ensureyourmonitorisconnectedtotheNVIDIAGPUport,configuredisplaysettingsinNVIDIAControlPanel,updatedriversusingDDUandcleaninstall,andsettheprimaryGPUtodiscreteinBIOS/UEFI.Restartaftereach

Java的僵局是什麼,您如何防止它? Java的僵局是什麼,您如何防止它? Aug 23, 2025 pm 12:55 PM

AdeadlockinJavaoccurswhentwoormorethreadsareblockedforever,eachwaitingforaresourceheldbytheother,typicallyduetocircularwaitcausedbyinconsistentlockordering;thiscanbepreventedbybreakingoneofthefournecessaryconditions—mutualexclusion,holdandwait,nopree

探索常見的Java設計模式與示例 探索常見的Java設計模式與示例 Aug 17, 2025 am 11:54 AM

Java設計模式是解決常見軟件設計問題的可複用方案。 1.Singleton模式確保一個類只有一個實例,適用於數據庫連接池或配置管理;2.Factory模式解耦對象創建,通過工廠類統一生成對像如支付方式;3.Observer模式實現自動通知依賴對象,適合事件驅動系統如天氣更新;4.Strategy模式動態切換算法如排序策略,提升代碼靈活性。這些模式提高代碼可維護性與擴展性但應避免過度使用。

如何在Java中使用可選的? 如何在Java中使用可選的? Aug 22, 2025 am 10:27 AM

useoptional.empty(),可選of(),andoptional.ofnullable()

PS油漆濾清器灰色固定 PS油漆濾清器灰色固定 Aug 18, 2025 am 01:25 AM

TheOilPaintfilterinPhotoshopisgreyedoutusuallybecauseofincompatibledocumentmodeorlayertype;ensureyou'reusingPhotoshopCS6orlaterinthefulldesktopversion,confirmtheimageisin8-bitperchannelandRGBcolormodebycheckingImage>Mode,andmakesureapixel-basedlay

使用Micronaut構建雲原生爪哇應用 使用Micronaut構建雲原生爪哇應用 Aug 20, 2025 am 01:53 AM

Micronautisidealforbuildingcloud-nativeJavaapplicationsduetoitslowmemoryfootprint,faststartuptimes,andcompile-timedependencyinjection,makingitsuperiortotraditionalframeworkslikeSpringBootformicroservices,containers,andserverlessenvironments.1.Microna

用於安全編碼的Java加密體系結構(JCA) 用於安全編碼的Java加密體系結構(JCA) Aug 23, 2025 pm 01:20 PM

理解JCA核心組件如MessageDigest、Cipher、KeyGenerator、SecureRandom、Signature、KeyStore等,它們通過提供者機制實現算法;2.使用SHA-256/SHA-512、AES(256位密鑰,GCM模式)、RSA(2048位以上)和SecureRandom等強算法與參數;3.避免硬編碼密鑰,使用KeyStore管理密鑰,並通過PBKDF2等安全派生密碼生成密鑰;4.禁用ECB模式,採用GCM等認證加密模式,每次加密使用唯一隨機IV,並及時清除敏

修復:Windows顯示'客戶不持有所需的特權” 修復:Windows顯示'客戶不持有所需的特權” Aug 20, 2025 pm 12:02 PM

runtheapplicationorcommandasadministratorByright-clickingandSelecting“ runasAdministrator” toensureeleeleeleeleviledprivilegesareAreDranted.2.checkuseracccountcontontrol(uac)uac)

See all articles