【发布时间】:2015-03-07 12:29:24
【问题描述】:
我有一个 Spring 应用程序,其中我不使用 xml 配置,仅使用 Java Config。一切都很好,但是当我尝试 test 时,我遇到了在测试中启用组件自动装配的问题。那么让我们开始吧。我有一个界面:
@Repository
public interface ArticleRepository extends CrudRepository<Page, Long> {
Article findByLink(String name);
void delete(Page page);
}
还有一个组件/服务:
@Service
public class ArticleServiceImpl implements ArticleService {
@Autowired
private ArticleRepository articleRepository;
...
}
我不想使用 xml 配置,因此对于我的测试,我尝试仅使用 Java 配置来测试 ArticleServiceImpl。所以为了测试目的我做了:
@Configuration
@ComponentScan(basePackages = {"com.example.core", "com.example.repository"})
public class PagesTestConfiguration {
@Bean
public ArticleRepository articleRepository() {
// (1) What to return ?
}
@Bean
public ArticleServiceImpl articleServiceImpl() {
ArticleServiceImpl articleServiceImpl = new ArticleServiceImpl();
articleServiceImpl.setArticleRepository(articleRepository());
return articleServiceImpl;
}
}
在 articleServiceImpl() 我需要放置 articleRepository() 的实例,但它是一个接口。如何使用新关键字创建新对象?是否可以不创建 xml 配置类并启用自动装配?测试时只使用 JavaConfigurations 可以启用自动装配吗?
【问题讨论】:
-
不,你没有。你有
@Autowired所以你不需要设置它。您需要将@EnableJpaRepositories放在您的配置类中,让 Spring Data JPA 为您创建 bean。 -
对于 ArticleServiceImpl 我也有 Awtowire 所以我也不需要写 articleServiceImpl() 吗?我对吗?我不明白 Spring 是如何知道为测试打开自动装配的。创建名为“articleServiceImpl”的 bean 时出错:注入自动装配的依赖项失败;嵌套异常是 org.springframework.beans.factory.BeanCreationException:无法自动装配字段:私有 com.musala.repository.ArticleRepository
-
@M.Deinum 有正确答案..
-
对于单元测试,根本不要使用真正的存储库。重构您的服务以使用构造函数注入并注入模拟存储库。这将使您的测试更加独立且速度更快。
标签: java xml spring spring-mvc autowired