目录
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 'org.junit.jupiter:junit-jupiter:5.9.3'

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 a   b;
    }

    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 (e.g., 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教程
1591
276
使用XSLT参数创建动态转换 使用XSLT参数创建动态转换 Aug 17, 2025 am 09:16 AM

XSLT参数是通过外部传递值来实现动态转换的关键机制,1.使用声明参数并可设置默认值;2.从应用程序代码(如C#)通过XsltArgumentList等接口传入实际值;3.在模板中通过$paramName引用参数控制条件处理、本地化、数据过滤或输出格式;4.最佳实践包括使用有意义的名称、提供默认值、分组相关参数并进行值验证。合理使用参数可使XSLT样式表具备高复用性和可维护性,相同样式表能根据不同输入产生多样化输出结果。

您目前尚未使用附上的显示器[固定] 您目前尚未使用附上的显示器[固定] Aug 19, 2025 am 12:12 AM

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

探索常见的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()

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

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

未找到操作系统[固定] 未找到操作系统[固定] Aug 17, 2025 am 09:10 AM

ifyourcomputershows“ operatatingsystemnotfound”,turtheSesteps:1.CheckBios/uefibootorder.2.verifydiskConnections.3.RepairbootLoaderSiversingWindowsRecovery.4.reassignDriveletterterterterterviadiskmanagement.5.ReinStallTheStalTheStaltheStallTheStallTheStallatingSystemyStemyfecteyStemifnecterifnecterifnequenecters。

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

See all articles