![](/img/trans.png)
[英]Unit Test Spring Boot with Controller -> Service -> Repository
[英]Unit testing a Spring Boot service class with(out) repository in JUnit
我正在研究具有以下结构的基于 Spring Boot 的网络服务:
控制器 (REST) --> 服务 --> 存储库(如某些教程中所建议)。
我的数据库连接 (JPA/Hibernate/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”的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 有资格作为此依赖项的自动装配候选者。 依赖注解:{@org.springframework.beans.factory.annotation.Autowired(required=true)}
为了完整起见:这是我的 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(){
...
}
}
使用 @SpringBootTest 和 @RunWith(SpringRunner.class) 加载上下文
@RunWith(SpringRunner.class)
@SpringBootTest
class Demo{
@Test
void contextLoad(){}
}
在您的测试中,Spring 将仅使用来自内部 ContextConfiguration 类的配置。 此类描述您的上下文。 在这种情况下,您只创建了服务 bean,没有创建存储库。 因此,将创建的唯一 bean 是 SessionService。 您应该在内部 ContextConfiguration 中添加 SessionRepository 的描述。 你的 JpaConfig 类不会在测试类中使用(你没有指定这个),只会在应用程序中使用。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.