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

如何自动将@InjectMocks注解的Player注入到Game中?

如何用@InjectMocks自动将Player注入到Game中?

你的代码结构如下:

class Player {
  @Inject
  Player(Tool tool) ...
}

class Game {
  @Inject
  Game(Player player) ...
}

@Mock Tool tool;

@InjectMocks Player player;

你希望直接通过@InjectMocks Game game;实现Player自动注入到Game,而非手动在@BeforeEach中实例化Game。

解决方案

给Player实例添加@Spy注解,让Mockito能识别它为可注入的依赖实例:

@Mock Tool tool;

@InjectMocks
@Spy
Player player;

@InjectMocks Game game;

这样Mockito初始化game时,会自动找到被@Spy标记的player实例,通过构造注入完成依赖注入。

补充说明

  • @InjectMocks会优先选用测试类中已存在的、被@Mock/@Spy标记的实例作为依赖。
  • @Spy可以把@InjectMocks创建的真实Player实例包装成Spy对象,让Mockito能够识别并注入到其他@InjectMocks标注的对象中。
  • 如果不需要Player的真实行为,也可以将player直接声明为@Mock,此时注入的会是Player的Mock实例,可根据测试需求选择。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.18 00:12:39