You need to enable JavaScript to run this app. 使用Mockito做Java服务单元测试时提示PlaneFactory的getPlane方法未定义
优惠活动
大模型
产品
解决方案
定价
更多

使用Mockito做Java服务单元测试时提示PlaneFactory的getPlane方法未定义

代码问题排查与修正

触发报错的直接原因

报错The method getPlane(String) is undefined for the type PlaneFactory的根源是你编写的PlaneFactory类代码结构残缺,编译器无法识别出合法的类方法:
你贴出的PlaneFactory代码中,getPlane方法写到midJet判断分支后就中断了,既没有补全剩余分支的返回逻辑,也没有给方法添加闭合大括号,连类本身的闭合大括号都缺失。编译器解析类结构时,会把这段残缺的代码判定为类内部的游离代码,根本不会把它识别为PlaneFactory的成员方法,自然会抛出“方法未定义”的错误。

PlaneFactory补全后的正确结构

@Component
public class PlaneFactory {
    public Plane getPlane(String planeType) {
        if (StringUtils.isBlank(planeType)) {
            throw new PlaneTypeNotFoundException();
        }
        if (planeType.equalsIgnoreCase("lightJet")) {
            return new LightJet();
        } else if (planeType.equalsIgnoreCase("midJet")) {
            return new MidJet();
        }
        // 非法入参兜底抛出明确异常
        throw new IllegalArgumentException("Unsupported plane type: " + planeType);
    }
}

测试类的连带问题

除了核心的类残缺问题,测试类本身存在多处会导致编译失败、测试逻辑失效的问题,需要逐一修正:

  • 类型大小写不匹配:Java是大小写敏感的语言,你定义的机型接口是大写开头的Plane,但测试类中声明变量时写成了小写private plane plane;,直接触发语法错误,需改为private Plane plane;
  • 方法名大小写不匹配:服务类中定义的接口方法是驼峰命名的getPlaneType(首字母P大写),测试类中调用时写成了小写p开头的getplaneType,会触发方法未定义报错,需严格保持拼写一致
  • Mock桩逻辑缺失:你创建了Plane类型的mock对象,但没有给它的getType()方法设置返回值,Mockito对未打桩的方法默认返回null,会导致测试过程无实际校验意义,需补充桩逻辑:
    when(plane.getType()).thenReturn("轻型喷气机");
    
  • 测试场景与入参不匹配:你想测试正常返回的业务逻辑时,传入了空字符串作为机型参数,按照真实工厂的逻辑,空字符串本身是会触发PlaneTypeNotFoundException的异常场景,不属于正常返回分支。测试正常返回逻辑时,应该传入如"lightJet"这类合法的机型值。

可直接运行的修正版测试类

public class PlaneCallerServiceImplTest {
    private PlaneFactory planeFactory;
    private PlaneCallerService planeCallerService;
    private Plane plane;

    @Before
    public void setUp() {
        planeFactory = mock(PlaneFactory.class);
        planeCallerService = new PlaneServiceImpl(planeFactory);
        plane = mock(Plane.class);
    }

    @Test
    public void testPlaneType() {
        // 匹配正常返回场景的合法入参
        String planeType = "lightJet";
        when(planeFactory.getPlane(planeType)).thenReturn(plane);
        // 给mock的Plane对象设置固定返回值
        when(plane.getType()).thenReturn("轻型喷气机");

        String result = planeCallerService.getPlaneType(planeType);
        // 用精准断言替代无意义的非空判断
        assertEquals("轻型喷气机 Plane has produced.", result);
    }
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.11.17 07:45:07