Spring Test + Mockito.mock - Spring因为尝试加载模拟bean @Autowired依赖项而失败

时间:2016-03-07 12:46:01

标签: spring mockito testng spring-test

我无法找出以下简单方案失败的原因:我有一个Spring应用程序,它带有一个从应用程序上下文加载Spring bean的过滤器:

public class MyFilter implements Filter{

    private IPermissionService permissionService;

    public void init(FilterConfig filterConfig) throws ServletException {
        WebApplicationContext ac = null;
        try{
            ac = WebApplicationContextUtils.getRequiredWebApplicationContext(filterConfig.getServletContext());
            permissionService = ac.getBean(PermissionServiceImpl.class);

PermissionServiceImpl有一个@Autowired属性dataSource,所以在我的TestNG测试中,我在Spring applicationContext中模拟它:

@Configuration
public class MyFilterSpringTestConfig{

    @Bean
    public IPermissionService permissionService(){
        return Mockito.mock(PermissionServiceImpl.class);
    }

MyTest的:

@Test
@WebAppConfiguration
@ContextConfiguration(classes=MyFilterSpringTestConfig.class)
public class MyFilterSpringTest extends BaseSpringFilterTest{

   ...

问题是在Spring初始化时我得到一个异常,抱怨不满足PermissionServiceImpl的dataSource依赖。因为我用模拟包装它,为什么它仍然失败?我怎么能解决它?

Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [javax.sql.DataSource] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true), @org.springframework.beans.factory.annotation.Qualifier(value=myDataSource)}

1 个答案:

答案 0 :(得分:2)

使用Mockito(或任何其他模拟框架)模拟类时,该类仍然是原始类的实例。随之而来的是它还包含所有注释和类信息。

因此,当您创建类的模拟时,它仍会检测到它上面的所有注释并尝试完全填充它。即其他情况@Autowire

要么不使用自动布线,要么不要模拟课程,但界面(不包含该信息)。