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

使用@MockBean时AttachmentService注入为null的问题(Java 11、Spring Boot 2.5.1环境)

解决Spring Boot测试中@Autowired依赖为null的问题

你碰到这个AttachmentService为null的问题,核心原因是你手动new出来的PostEventHandler实例根本不在Spring容器的管理范围内,Spring没法把你用@MockBean模拟的AttachmentService注入进去,自然就会是null啦。下面给你两种可行的解决方案:

方案一:让Spring容器注入PostEventHandler到测试类

既然PostEventHandler标注了@Component,Spring会自动管理它的实例。你只需要在测试类里用@Autowired把它注入进来,而不是自己手动new。这样Spring会自动把@MockBean的AttachmentService装配到这个实例中。

修改后的测试类代码:

@SpringBootTest 
public class PostEventHandlerTest { 
    @MockBean 
    private AttachmentService attachmentService; 

    @Autowired // 让Spring注入容器管理的PostEventHandler实例
    private PostEventHandler postEventHandler; 

    @Test 
    public void handlePostBeforeCreateTest() throws Exception { 
        Post post = new Post("First Post", "Post Added", null, null, "", ""); 
        Mockito.when(attachmentService.storeFile("abc.txt", "")).thenReturn(new Attachment()); 
        // 直接使用Spring注入的实例,不要手动new
        postEventHandler.handlePostBeforeCreate(post); 
        verify(attachmentService, times(1)).storeFile("abc.txt", ""); 
    } 
}

方案二:用Mockito的@InjectMocks自动注入依赖

如果你不想加载整个Spring上下文(想写更轻量化的单元测试),可以用Mockito的@InjectMocks注解,自动把模拟的依赖注入到PostEventHandler实例中。

修改后的测试类代码:

@ExtendWith(MockitoExtension.class) // 用Mockito扩展替代SpringBootTest,更轻量化
public class PostEventHandlerTest { 
    @Mock // 模拟AttachmentService
    private AttachmentService attachmentService; 
    @Mock // 必须同时模拟PostRepository,否则注入时会null
    private PostRepository postRepository;

    @InjectMocks // 让Mockito把上面的@Mock实例注入到这个对象中
    private PostEventHandler postEventHandler; 

    @Test 
    public void handlePostBeforeCreateTest() throws Exception { 
        Post post = new Post("First Post", "Post Added", null, null, "", ""); 
        Mockito.when(attachmentService.storeFile("abc.txt", "")).thenReturn(new Attachment()); 
        postEventHandler.handlePostBeforeCreate(post); 
        verify(attachmentService, times(1)).storeFile("abc.txt", ""); 
    } 
}

注意:这种方式下,PostEventHandler中所有用@Autowired标注的依赖都需要被模拟(比如PostRepository),否则Mockito无法完成注入,依然会出现null。

为什么原写法会失败?

Spring的依赖注入(@Autowired)只对Spring容器创建并管理的实例生效。当你手动new PostEventHandler()时,这个对象完全脱离了Spring的控制,Spring根本不知道它的存在,自然不会帮你注入任何依赖。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.30 04:57:47