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

JUnit Eclemma测试覆盖率时getDeviceList方法全分支未覆盖求助

问题根因
  • 你直接对待测试的DeviceService类本身创建了Mock对象,Mockito的Mock对象会完全接管类的所有方法逻辑,你通过when()配置的返回值会直接返回,根本不会执行原类的getDeviceList真实代码,所以Eclemma统计不到任何代码执行记录,自然显示所有分支未覆盖。
  • 你方法里的if (StringUtils.hasText(device))判断共有2个分支:入参符合hasText条件走if分支、不符合走else返回null,两个分支都需要实际执行到才能消除All 2 branches missed的提示。
正确测试方案

待测试的getDeviceList没有外部依赖,不需要Mock任何组件,直接实例化DeviceService写测试用例即可,参考代码如下:

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

public class DeviceServiceTest {
    // 直接实例化待测试类,不要Mock
    private DeviceService deviceService = new DeviceService();

    // 覆盖if分支:入参为有效非空白字符串
    @Test
    public void getDeviceList_withValidInput_returnSplitList() {
        List<String> result = deviceService.getDeviceList("Smartphone,Watch");
        Assertions.assertEquals(List.of("Smartphone", "Watch"), result);
    }

    // 覆盖else分支:入参为null/空串/全空白
    @Test
    public void getDeviceList_withBlankInput_returnNull() {
        Assertions.assertNull(deviceService.getDeviceList(null));
        Assertions.assertNull(deviceService.getDeviceList(""));
        Assertions.assertNull(deviceService.getDeviceList("  "));
    }
}

如果确实存在需要Mock DeviceService部分方法的场景,可改用@Spy注解创建间谍对象,Spy默认执行原类真实逻辑,仅你指定的方法会走Mock返回,也能正常统计代码覆盖率。

内容的提问来源于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 08:54:06