【发布时间】:2013-10-29 09:31:50
【问题描述】:
我正在开发一个基于 Spring Boot 的 Web 服务,其结构如下:
控制器 (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(){
[...]
}
}
但我得到以下异常:
引起:org.springframework.beans.factory.BeanCreationException: 创建名为“sessionService”的 bean 时出错:注入自动装配 依赖失败;嵌套异常是 org.springframework.beans.factory.BeanCreationException:不能 自动装配字段:私有 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(){
...
}
}
【问题讨论】:
标签: java spring junit spring-boot