You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何编写JUnit单元测试实现getDeviceList方法的全代码覆盖

getDeviceList 方法全代码覆盖JUnit测试用例

以下示例基于JUnit 5编写,覆盖所有分支逻辑与边界输入场景,可实现100%代码覆盖率。

覆盖场景梳理

要实现全代码覆盖,需要覆盖if判断的true/false两个分支,同时覆盖split逻辑的各类常见/边界输入:

  • 入参为null:触发StringUtils.hasText返回false,返回null
  • 入参为空字符串"":触发StringUtils.hasText返回false,返回null
  • 入参为全空白字符串(如" "):触发StringUtils.hasText返回false,返回null
  • 入参为单个设备名称无分隔符:验证单元素拆分逻辑正确
  • 入参为多个设备用逗号分隔:验证逗号拆分逻辑正确
  • 入参为逗号、空格混合分隔:验证正则[, ]的多分隔符拆分逻辑正确
  • 入参首尾带分隔符:验证边缘位置分隔符的处理结果符合方法原有逻辑

测试代码实现

注意:原方法使用的StringUtils.hasText默认是Spring框架的org.springframework.util.StringUtils,如果你的项目用的是Apache Commons的StringUtils,判断逻辑一致,无需修改测试用例。

import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
import java.util.List;
import static org.junit.jupiter.api.Assertions.*;

// 这里替换为你自己的业务类所在的包
import com.yourpackage.YourBusinessClass;

class DeviceListTest {

    // 初始化待测试的业务类实例
    private final YourBusinessClass testClass = new YourBusinessClass();

    @Test
    @DisplayName("入参为null时返回null")
    void testGetDeviceListWithNull() {
        List<String> result = testClass.getDeviceList(null);
        assertNull(result);
    }

    @Test
    @DisplayName("入参为空字符串时返回null")
    void testGetDeviceListWithEmptyStr() {
        List<String> result = testClass.getDeviceList("");
        assertNull(result);
    }

    @Test
    @DisplayName("入参为全空白字符串时返回null")
    void testGetDeviceListWithBlankStr() {
        List<String> result = testClass.getDeviceList("   ");
        assertNull(result);
    }

    @Test
    @DisplayName("入参为单个设备名时返回单元素列表")
    void testGetDeviceListWithSingleDevice() {
        List<String> result = testClass.getDeviceList("Apple");
        assertEquals(1, result.size());
        assertEquals("Apple", result.get(0));
    }

    @Test
    @DisplayName("入参为逗号分隔的多个设备名时返回对应列表")
    void testGetDeviceListWithCommaSeparated() {
        List<String> result = testClass.getDeviceList("Apple,Samsung,Xiaomi");
        assertEquals(3, result.size());
        assertEquals(List.of("Apple", "Samsung", "Xiaomi"), result);
    }

    @Test
    @DisplayName("入参为逗号、空格混合分隔的设备名时按规则拆分")
    void testGetDeviceListWithMixedSeparator() {
        List<String> result = testClass.getDeviceList("Apple Samsung,Xiaomi");
        assertEquals(3, result.size());
        assertEquals(List.of("Apple", "Samsung", "Xiaomi"), result);
    }

    @Test
    @DisplayName("入参首尾带分隔符时拆分结果包含空字符串元素")
    void testGetDeviceListWithSeparatorAtEdge() {
        List<String> result = testClass.getDeviceList(",Apple,Xiaomi ");
        assertEquals(4, result.size());
        assertEquals(List.of("", "Apple", "Xiaomi", ""), result);
    }
}

补充说明

如果你的项目使用的是JUnit 4,只需要把注解替换为org.junit.Test,断言方法改用org.junit.Assert的对应静态方法即可,测试场景完全通用。

内容的提问来源于stack exchange,提问作者MyDev2020

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.29 13:45:00