【发布时间】:2019-08-14 17:51:55
【问题描述】:
我们写了下面2个类
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = {TestConfig.class})
public class AbcFilterTest {
@Autowired
private AbcUtils abcUtils;
@Autowired
private AbcRepository abcRepository;
@Test
public void testFilter() {
MockHttpServletRequest httpServletRequest = new MockHttpServletRequest();
MockHttpServletResponse httpServletResponse = new MockHttpServletResponse();
MockFilterChain mockChain = new MockFilterChain();
}
}
@Configuration
@ComponentScan(basePackageClasses = {AbcUtils.class, AbcRepository.class,})
public class TestConfig {
}
为了运行一个测试类,我需要 AbcUtilsclass 和 AbcRepository 接口(扩展 CurdRepository)的实例,它们在我正在测试的类中自动装配。第一个有 @Component 而第二个有@Repositry 在它上面。你可以看,在我的测试类中,我已经像上面的代码一样使用组件扫描自动连接了 util 和存储库类。Spring 框架实时为存储库接口创建了实现类,但是在运行测试用例时,我遇到了错误
引起:org.springframework.beans.BeanInstantiationException: 无法实例化 [com.a.b.c.persistence.AbcRepository]:指定 类是一个接口。
请建议如何使这个测试类工作。请注意,我们没有使用 Spring Boot 和 Mockito。我们正在进行集成测试。 我们正在使用 Spring rest 和 Spring Data JPA with hibernate。
【问题讨论】:
-
我认为您需要发布您的配置文件 TestConfig.class,因为我们在您的代码中没有看到您告诉 Spring 您将使用 Spring Data JPA 的任何地方。还是您使用的是 Spring Boot?只需确保您删除了测试配置中可能包含的所有密码或私人信息。
-
AbcRepository 是一个接口,不能把它当作一个类来对待
-
你需要用一些JPA实现来扩展
AbcRepository,或者编写这个接口的自定义实现。
标签: spring junit spring-data-jpa spring-test