单元测试弹簧引导服务类JUnit中(出)库

问题描述 投票:5回答:1

我的工作有以下结构弹簧启动基于Web服务:

控制器(REST) - >服务 - >库(在一些教程建议)。

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

现在,我想编写简单的测试,在我的服务类中的方法,但我真的不知道如何ApplicationContext中加载到我的测试类,以及如何嘲笑JPA /存储库。

这是多远我就来了:

我的服务类

@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(){
    [...]
  }
}

但我得到以下异常:

org.springframework.beans.factory.BeanCreationException:由造成错误创建名为“sessionService”豆:自动装配依赖注入失败;嵌套的例外是org.springframework.beans.factory.BeanCreationException:无法自动装配领域:私人com.myApp.SessionRepository com.myApp.SessionService.sessionRepository;嵌套异常是org.springframework.beans.factory.NoSuchBeanDefinitionException:无类型[com.myApp.SessionRepository]的排位豆找到依赖性:预期至少1豆,其有资格作为自动装配候选这种依赖性。依赖注解:{@ org.springframework.beans.factory.annotation.Autowired(所需=真)}

为了完整:这是我的JPA @Configuration:

@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(){
  ... 
   }
}
java spring junit spring-boot
1个回答
0
投票

在您的测试Spring将使用配置只能从内部ContextConfiguration类。本课程介绍你的背景。在这种情况下,你只创建服务豆,没有仓库。因此,将要创建的唯一bean是SessionService。你应该在内部ContextConfiguration添加SessionRepository的描述。你JpaConfig类将不会在测试类中使用(你不指定此),只有在应用程序。

© www.soinside.com 2019 - 2024. All rights reserved.