Spring测试抛出org.springframework.beans.factory.NoSuchBeanDefinitionException:没有类型的限定bean

时间:2018-03-17 02:01:02

标签: spring junit spring-test

我的网络应用程序运行正常。但是当我试图为我的dao类添加测试用例时。我在这篇文章的最后一篇中提到了错误

我在同一个文件夹中有UserDaoTest和UserDaoImpl / UserDao

这是UserDaoTest

    package com.User.orm.dao;

    @RunWith(SpringJUnit4ClassRunner.class)
    @ContextConfiguration(loader=AnnotationConfigContextLoader.class)

    @TestExecutionListeners({ DependencyInjectionTestExecutionListener.class,
            DbUnitTestExecutionListener.class })
    public class UserDaoTest {

        @Autowired
        private UserDao UserDao;

        @Test
        public void testFind() throws Exception {
            List<UserProfile> up = UserDao.searchUsers("test",null);
            System.out.println("test");

        }

    }

这是UserDaoImpl

    package com.User.orm.dao;


    @Component
    public class UserDaoImpl extends GenericDAOImpl<User>  implements UserDao{


        public UserResponseDTO searchUsers(String user, Filter filter){}

    }

但低于错误

Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [com.User.orm.dao.UserDao] 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)}

1 个答案:

答案 0 :(得分:1)

为单元测试创​​建配置类。通过实现“@Configuration”注释来定义配置类。然后使用@ComponentScan从包中获取bean。

 @Configuration
 @ComponentScan("com.User.orm.dao")
 public class AppConfig {

    @Bean
    public UserDao userDao() {
        return new UserDao();
    }

  }

确保UserDao具有@Component或@Service注释。