java – 在JUnit中使用(out)存储库对Spring Boot服务类进行单元测试

我正在开发基于Spring boot的webservice,其结构如下:

控制器(REST) – >服务 – >存储库(如某些教程中所述).

我的数据库连接(JPA / Hibernate / MySQL)在@Configuration类中定义. (见下文)

现在我想为我的Service类中的方法编写简单的测试,但我真的不明白如何将ApplicationContext加载到我的测试类中以及如何模拟JPA / Repositories.

这是我走了多远:

我的服务类

@Component
public class SessionService {
    @Autowired
    private SessionRepository sessionRepository;
    public void MethodIWantToTest(int i){
    };
    [...]
}

我的考试班:

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(loader = AnnotationConfigContextLoader.class)
public class SessionServiceTest {

    @Configuration
    static class ContextConfiguration {
        @Bean
        public SessionService sessionService() {
            return new SessionService();
        }
    }

    @Autowired
    SessionService sessionService;
    @Test
    public void testMethod(){
    [...]
  }
}

但我得到以下例外:

Caused by: org.springframework.beans.factory.BeanCreationException:
Error creating bean with name ‘sessionService’: Injection of autowired
dependencies failed; nested exception is
org.springframework.beans.factory.BeanCreationException: Could not
autowire field: private com.myApp.SessionRepository
com.myApp.SessionService.sessionRepository; nested exception is
org.springframework.beans.factory.NoSuchBeanDefinitionException: No
qualifying bean of type [com.myApp.SessionRepository] 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)}

为了完整性:这是我的@Configuration for jpa:

@Configuration
@EnableJpaRepositories(basePackages={"com.myApp.repositories"})
@EnableTransactionManagement
public class JpaConfig {


    @Bean
    public ComboPooledDataSource dataSource() throws PropertyVetoException, IOException {
        ...
    }

   @Bean
    public LocalContainerEntityManagerFactoryBean entityManagerFactory(DataSource dataSource, JpaVendorAdapter jpaVendorAdapter) {
        ...
    }


    @Bean
    public JpaVendorAdapter jpaVendorAdapter() {
        ...
    }

    @Bean
    public PlatformTransactionManager transactionManager(EntityManagerFactory entityManagerFactory) {
   ...
    }

    @Bean
    public PersistenceExceptionTranslationPostProcessor exceptionTranslation(){
  ... 
   }
}
最佳答案
在您的测试中,Spring将仅使用内部ContextConfiguration类中的配置.该类描述了您的上下文.在此上下文中,您只创建了服务bean而没有存储库.因此,唯一将创建的bean是SessionService.您应该在内部ContextConfiguration中添加SessionRepository的描述.您的JpaConfig类不会在测试类中使用(您不指定此类),仅在应用程序中使用.

转载注明原文:java – 在JUnit中使用(out)存储库对Spring Boot服务类进行单元测试 - 代码日志