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

Ale*_*lex 5 java junit spring 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){
    };
    [...]
}
Run Code Online (Sandbox Code Playgroud)

我的考试班:

@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(){
    [...]
  }
}
Run Code Online (Sandbox Code Playgroud)

但我得到以下例外:

引起:org.springframework.beans.factory.BeanCreationException:创建名为'sessionService'的bean时出错:注入自动连接的依赖项失败; 嵌套异常是org.springframework.beans.factory.BeanCreationException:无法自动装配字段:private com.myApp.SessionRepository com.myApp.SessionService.sessionRepository; 嵌套异常是org.springframework.beans.factory.NoSuchBeanDefinitionException:找不到[com.myApp.SessionRepository]类型的限定bean用于依赖:预期至少有1个bean符合此依赖关系的autowire候选者.依赖注释:{@ 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(){
  ... 
   }
}
Run Code Online (Sandbox Code Playgroud)

mvb*_*b13 0

在您的测试中,Spring 将仅使用内部 ContextConfiguration 类中的配置。本课程描述了您的背景。在此上下文中,您仅创建了服务 bean,没有创建存储库。因此,唯一要创建的 bean 是 SessionService。您应该在内部 ContextConfiguration 中添加 SessionRepository 的描述。您的 JpaConfig 类不会在测试类中使用(您没有指定它),仅在应用程序中使用。