【问题标题】:How to write integration/system test with Spring Boot to test service with repository如何使用 Spring Boot 编写集成/系统测试以使用存储库测试服务
【发布时间】:2018-11-24 01:34:15
【问题描述】:

我在 Spring Boot 应用程序中有 @Service,它正在解析文件,然后使用 Spring Data JPA 将其存储到数据库中。我想用改变这个映射的所有逻辑来测试这个解析。因此,为此我需要在测试中将映射存储在 DB 中。

@Service  
public class ParsingService {
    @Autowired
    private StoringInDBRepository storingInDBRepository;
}

@Repository
public interface StoringInDBRepository extends JpaRepository<MyEntity, String> {

问题是在使用注释@SpringBootTest 进行测试期间,我不想加载整个上下文,而只想加载我的 ParsingService。 当我写作时:

@RunWith(SpringRunner.class)
@SpringBootTest(classes = {ParsingService.class})
public class ParsingServiceTest{

    @Test
    public void someTest(){
    }
}

无法初始化此测试,因为我没有在 @SpringBootTest 注释中加载 StoringInDBRepository。但是我可以做到,因为 StoringInDBRepository 是一个接口。仅当我正在测试存储库层时,根据 javadoc 使用 @DataJpaTest 才是正确的。不推荐使用@DataJpaTest 和@SpringBootTest。

我应该如何测试这些服务? 提前致谢。

【问题讨论】:

  • 你可以模拟存储库 bean
  • @akuma8 不,因为那样它们将无法按预期工作。我需要真正的对象将功能。不是嘲笑

标签: java spring spring-boot integration-testing


【解决方案1】:

所以,经过所有调查,我找到了几个解决方案。我选择使用

启用存储库和服务
@SpringBootTest(classes = {ParsingService.class})
@EnableJpaRepositories(basePackages = "com.my.repository")
@EntityScan("com.my.entity")
@AutoConfigureDataJpa

这是一种解决方法。而且我认为这不是最好的。另一个解决方案是创建一个 @TestConfiguration ,它将返回您的服务和所有使用 @DataJpaTest 注释来启用存储库类。在这种情况下,您应该使用 @SpringBootTest 注解

【讨论】:

    【解决方案2】:

    您可以使用@SpyBean 来获得您想要的东西。它相当容易使用。

    但是 - 您实际上不需要以这种方式对其进行测试。因为通过测试您的应用程序上下文,您可以确保所有类都按应有的方式注入/自动装配。然后分别用 mocks 在服务级别上测试方法。最后,使用@DataJpaTest 在存储库/数据库级别对其进行测试。

    所以你可以很好地解耦你的测试:集成测试/单元测试/存储库测试

    没有必要在一个类或测试方法中将所有这三件事紧密结合。

    【讨论】:

    • 嗯,这不是我想要的解决方案。我想成对测试所有组件,我需要一起测试它。我也有双重测试。感谢您的帮助)
    猜你喜欢
    • 2015-08-02
    • 1970-01-01
    • 2018-02-19
    • 1970-01-01
    • 1970-01-01
    • 2021-07-28
    • 1970-01-01
    • 2015-01-01
    • 1970-01-01
    相关资源
    最近更新 更多