简体   繁体   English

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

[英]Unit testing a Spring Boot service class with(out) repository in JUnit

I am working on a spring boot based webservice with following structure:我正在研究具有以下结构的基于 Spring Boot 的网络服务:

Controller (REST) --> Services --> Repositories (as suggested in some tutorials).控制器 (REST) --> 服务 --> 存储库(如某些教程中所建议)。

My Database Connection (JPA/Hibernate/MySQL) is defined in a @Configuration class.我的数据库连接 (JPA/Hibernate/MySQL) 是在 @Configuration 类中定义的。 (see below) (见下文)

Now I'd like to write simple tests for methods in my Service classes, but I don't really understand how to load ApplicationContext into my test classes and how to mock the JPA / Repositories.现在我想为我的服务类中的方法编写简单的测试,但我真的不明白如何将 ApplicationContext 加载到我的测试类中以及如何模拟 JPA/存储库。

This is how far I came:这是我走了多远:

My service class我的服务班

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

My test class:我的测试班:

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

But I get following exception:但我得到以下异常:

Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'sessionService': Injection of autowired dependencies failed;引起:org.springframework.beans.factory.BeanCreationException:创建名为“sessionService”的bean时出错:自动装配依赖项的注入失败; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: private com.myApp.SessionRepository com.myApp.SessionService.sessionRepository;嵌套异常是 org.springframework.beans.factory.BeanCreationException:无法自动装配字段: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.嵌套异常是 org.springframework.beans.factory.NoSuchBeanDefinitionException: 找不到类型为 [com.myApp.SessionRepository] ​​的合格 bean 依赖项:预期至少有 1 个 bean 有资格作为此依赖项的自动装配候选者。 Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)}依赖注解:{@org.springframework.beans.factory.annotation.Autowired(required=true)}

For completeness: here's my @Configuration for jpa:为了完整起见:这是我的 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(){
  ... 
   }
}

use @SpringBootTest and @RunWith(SpringRunner.class) to load the context使用 @SpringBootTest 和 @RunWith(SpringRunner.class) 加载上下文

@RunWith(SpringRunner.class)
@SpringBootTest
class Demo{
    @Test
    void contextLoad(){}
}

In your test Spring will use configuration only from inner ContextConfiguration class.在您的测试中,Spring 将仅使用来自内部 ContextConfiguration 类的配置。 This class describes your context.此类描述您的上下文。 In this context you created only service bean and no repository.在这种情况下,您只创建了服务 bean,没有创建存储库。 So the only bean that will be created is SessionService.因此,将创建的唯一 bean 是 SessionService。 You should add description of SessionRepository in inner ContextConfiguration.您应该在内部 ContextConfiguration 中添加 SessionRepository 的描述。 Your JpaConfig class will not be used in test class(you don't specify this), only in application.你的 JpaConfig 类不会在测试类中使用(你没有指定这个),只会在应用程序中使用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM