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

未使用SpringExtension/SpringBootTest,BeanUtils为何能配合MockitoExtension工作?

问题描述

我仅在测试类中配置了MockitoExtension,未使用SpringExtension或@SpringBootTest,但MyService的createMyService()方法中调用的org.springframework.beans.BeanUtils却能正常运行,特此请教该现象的原因。

相关代码如下:

@ExtendWith(MockitoExtension.class)
class MyServiceTest {

    @InjectMocks
    MyService myService;

    @Mock
    MyRepository myRepository;

    @Test
    public void createMyTest() throws BusinessException {
        myService.createMyService();
    }
}

void createMyService(){
    BeanUtils.copyProperties(createdDocumentType, documentTypeCreateResponse);
}
原因解析

这是因为BeanUtils.copyProperties是一个纯静态工具方法,它的运行完全不需要依赖Spring容器的上下文环境:

  • 它的实现逻辑仅基于Java反射API完成属性拷贝,不需要任何Spring Bean初始化或容器支持
  • 只要测试类路径中包含spring-beans依赖包,就能直接调用这个静态方法,和是否启用SpringExtension或@SpringBootTest启动Spring容器无关
  • MockitoExtension仅负责创建Mock对象、注入依赖到测试类,不会影响静态工具方法的调用,只要依赖存在,静态方法就能正常执行

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.17 21:20:28