Day 18:单元测试与 JUnit

理论知识

1. 什么是单元测试?
单元测试是对软件中最小的功能单元(如方法或类)进行验证的测试,确保其行为符合预期。
作用:
  • 提高代码质量,避免潜在的缺陷。
  • 支持重构和快速验证功能。
  • 提高开发效率。
2. JUnit 的核心注解:
  • @Test:标记为测试方法。
  • @Before:在每个测试方法之前执行,用于初始化。
  • @After:在每个测试方法之后执行,用于清理资源。
  • @BeforeClass@AfterClass:在所有测试方法之前和之后执行,适合静态资源初始化和清理。
3. 常用断言:
  • assertEquals(expected, actual):断言两个值相等。
  • assertTrue(condition):断言条件为 true
  • assertThrows(Exception.class, () -> method()):断言方法抛出指定异常。

实践操作:为字符串工具类编写单元测试

工具类代码:StringUtil.java

public class StringUtil {
    public static String reverse(String input) {
        if (input == null) {
            throw new IllegalArgumentException("Input cannot be null");
        }
        return new StringBuilder(input).reverse().toString();
    }

    public static String concatenate(String str1, String str2) {
        if (str1 == null || str2 == null) {
            throw new IllegalArgumentException("Strings cannot be null");
        }
        return str1 + str2;
    }
}

单元测试代码:StringUtilTest.java

import org.junit.After;
import org.junit.Before;
import org.junit.Test;

import static org.junit.Assert.*;

public class StringUtilTest {
    @Before
    public void setUp() {
        System.out.println("Setting up test environment...");
    }

    @After
    public void tearDown() {
        System.out.println("Cleaning up test environment...");
    }

    @Test
    public void testReverse() {
        String input = "hello";
        String expected = "olleh";
        assertEquals("Reverse method failed", expected, StringUtil.reverse(input));
    }

    @Test
    public void testConcatenate() {
        String str1 = "hello";
        String str2 = "world";
        String expected = "helloworld";
        assertEquals("Concatenate method failed", expected, StringUtil.concatenate(str1, str2));
    }

    @Test
    public void testReverseWithNull() {
        assertThrows(IllegalArgumentException.class, () -> StringUtil.reverse(null));
    }

    @Test
    public void testConcatenateWithNull() {
        assertThrows(IllegalArgumentException.class, () -> StringUtil.concatenate("hello", null));
    }
}

使用场景

  1. 持续集成:将单元测试集成到 CI/CD 流程中,自动验证代码质量。
  2. 重构保障:在重构代码时,通过单元测试快速验证功能是否被破坏。
  3. Bug 修复:为修复的 Bug 编写单元测试,防止相同问题重复出现。

总结

单元测试是保障代码质量的关键工具。通过 JUnit,可以方便地验证方法行为、捕获异常,并提升代码的健壮性。在实际开发中,单元测试与自动化工具结合,能有效提高开发效率和代码稳定性。

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值