首页 > 解决方案 > DataJpaTest 与单个自动装配测试 bean

问题描述

我想创建一个测试,它针对@Service我项目中的一个服务类 ( )。

我的服务类有两种依赖:

我的服务仅依赖于其他服务或存储库。存储库没有依赖关系——想象一下 JPA 存储库接口。

我想出了以下解决方案,效果很好:

@DataJpaTest
class FooServiceTests {

    @Autowired
    private FooRepository fooRepository;

    @MockBean
    private BarService barService;

    @Test
    void testService() {
        FooService fooService = new FooService(barService, fooRepository);
        Assertions.assertNotNull(barService);
        Assertions.assertNotNull(fooRepository);
    }

}

我的问题是,这个解决方案是否有替代方案,它不需要手动组装测试的 bean。一个解决方案,通过使用模拟服务和真实(H2)存储库,让 Spring 为我组装 bean。一种解决方案,它允许被测试的 bean 依赖@Autowired于私有字段。像这样的东西:(显然不起作用):

@DataJpaTest
@ContextConfiguration(classes = FooService.class)
class FooService2Tests {

    @MockBean
    private BarService barService;

    @Autowired
    private FooService fooService;

    @Test
    void testService() {
        Assertions.assertNotNull(fooService);
        Assertions.assertNotNull(barService);
        Assertions.assertNotNull(fooService.getBarService());
        Assertions.assertNotNull(fooService.getFooRepository());
    }

}

我想避免使用@SpringBootTest. 如果某些答案表明是这样,那么它应该解释一下,为什么这是最好的方法。

标签: javaspringspring-bootspring-data-jpaspring-test

解决方案


推荐阅读