使用Mockito >=5.1.0模拟嵌套Bean时触发NoSuchBeanDefinitionException
解决方案
方案1:显式指定Mock Bean的类型
Mockito 5.1.0中,Mockito.mock(Class<T>, String)生成的动态代理对象,Spring无法自动推断其代理的目标类型。只需在XML的bean定义中添加type属性,明确指定Bean的实际类型为ApiClient即可:
修改后的Mock Bean配置:
<bean id="apiClient" class="org.mockito.Mockito" factory-method="mock" type="org.example.ApiClient"> <constructor-arg type="java.lang.Class" value="org.example.ApiClient" /> <constructor-arg type="java.lang.String" value="mockedApiClient" /> </bean>
方案2:改用无名称参数的Mock方法
如果不需要指定Mock名称,可使用Mockito的单参数mock方法,同时保留type属性确保Spring识别类型:
<bean id="apiClient" class="org.mockito.Mockito" factory-method="mock" type="org.example.ApiClient"> <constructor-arg type="java.lang.Class" value="org.example.ApiClient" /> </bean>
方案3:切换到注解驱动的Mock方式
若项目支持Spring Boot或注解配置,可使用@MockBean注解替代XML配置,更简洁且不易出错:
@ExtendWith(SpringExtension.class) @ContextConfiguration(locations = "classpath:testApplicationContext.xml") public class MainTest { @Autowired SomeBo someBo; @MockBean ApiClient apiClient; @Test public void test() { assertThat(someBo).isNotNull(); System.out.println(someBo); } }
原理说明
Spring通过工厂方法创建Bean时,对于Mockito生成的动态代理类,5.1.0版本中Spring无法像5.0.0那样自动识别其代理的目标类型。显式指定type属性后,Spring会将该Bean注册为指定类型的实例,@Autowired依赖注入时就能匹配到对应的Bean。
内容的提问来源于stack exchange,提问作者hmmnrst
相关产品推荐
相关产品推荐

