【问题标题】:How to have bean of repository interface of spring data jpa during run of test cases如何在测试用例运行期间拥有spring data jpa的存储库接口bean
【发布时间】: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


【解决方案1】:

如果你想在数据库中写一些东西,扫描AbcUtils.classAbcRepository.class 是不够的。您需要扫描包含您的 DataSource 定义和相关配置的配置。由于测试也会像 Spring bean 一样被实例化,所以测试类需要实现 ApplicationContextAware 接口:

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = {"/config.xml"}) 
public class TestClass implements ApplicationContextAware{
  @Autowired
  Repository repository;
//....
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-02-13
    • 2019-01-23
    • 1970-01-01
    • 2017-07-17
    • 2016-01-08
    • 2014-06-19
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多