测试基于CrudRepository的ExpeditionService时Repository注入为空的解决方法
解决@DataJpaTest中Repository注入为空的问题
出现Repository为空的核心原因是:你手动实例化ExpeditionService时,Spring的测试上下文并没有将它管理的Repository代理实例注入进去——手动new的对象不在Spring容器的管控范围内,自然无法自动填充依赖。以下是几种可行的解决方式:
方式1:让Spring自动注入ExpeditionService(推荐)
放弃手动实例化,直接在测试类中通过@Autowired注入ExpeditionService,前提是你的ExpeditionService已经是Spring管理的Bean(比如标注了@Service注解)。
示例代码:
@DataJpaTest class ExpeditionServiceTest { @Autowired private ExpeditionService expeditionService; // 按需注入Repository,用于测试数据准备 @Autowired private ArticleRepository articleRepository; @Test void testExpeditionLogic() { // 编写测试逻辑 } }
对应的ExpeditionService需要是Spring组件,且用构造函数注入依赖(这是Spring推荐的依赖注入方式):
@Service public class ExpeditionService { private final ArticleRepository articleRepository; private final CustomerRepository customerRepository; private final AddressRepository addressRepository; public ExpeditionService(ArticleRepository articleRepository, CustomerRepository customerRepository, AddressRepository addressRepository) { this.articleRepository = articleRepository; this.customerRepository = customerRepository; this.addressRepository = addressRepository; } // 业务方法实现 }
方式2:手动从Spring上下文获取Repository并初始化Service
如果因特殊需求必须手动实例化ExpeditionService,可以先通过@Autowired获取Spring管理的Repository实例,再在测试初始化阶段传入Service的构造函数:
@DataJpaTest class ExpeditionServiceTest { @Autowired private ArticleRepository articleRepository; @Autowired private CustomerRepository customerRepository; @Autowired private AddressRepository addressRepository; private ExpeditionService expeditionService; @BeforeEach void setUp() { expeditionService = new ExpeditionService(articleRepository, customerRepository, addressRepository); } @Test void testExpeditionLogic() { // 编写测试逻辑 } }
方式3:确保Spring能扫描到ExpeditionService
如果测试类和ExpeditionService不在同一包或子包下,Spring可能无法自动扫描到它。此时可以在@DataJpaTest上添加@Import注解,显式指定要加载的Service类:
@DataJpaTest @Import(ExpeditionService.class) class ExpeditionServiceTest { @Autowired private ExpeditionService expeditionService; // ...测试方法 }
内容的提问来源于stack exchange,提问作者fnyve
相关产品推荐
相关产品推荐

