首页 > 解决方案 > Spring Boot @RestClientTest 如何使用真实服务器进行测试(不是模拟)

问题描述

我需要针对 REST API 创建集成测试。我的服务使用 Resttemplate 作为 HTTP 客户端。客户端代码是从 swagger 文件生成的。

运行测试会产生错误java.lang.AssertionError: No further requests expected: HTTP GET

似乎测试是针对模拟服务器运行的。如何让测试在真实服务器上运行?

这是我当前的测试设置(想要剪掉一个最小的测试框架以获得快速测试 - 启动完整的上下文太慢了):

@RunWith(SpringRunner.class)
@Import(value = { TpzConfig.class, TpzServiceRestImpl.class, ManufacturingPlantPhPmMapperImpl.class,
        ProductHierarchyMapperImpl.class, PlantMapperImpl.class })
@ActiveProfiles(profiles = { "tpz" })
@RestClientTest
public class TpzServiceRestImplTest {

    @Autowired
    private TpzService to;

    @MockBean
    private ProductionPlantService ppService;

    @MockBean
    private ProductHierarchyService phService;

    @Test
    public void test() {
        List<ProductManufacturer> pmByProductHierarchy = to.pmByProductHierarchy("001100909100100388");

    }

}

我需要@RestClientTest一个 RestTemplateBuilder 的 bean。

有没有办法配置@RestClientTest使用真实服务器(类似于@DataJpaTest我可以配置不使用 h2 的地方)?

标签: spring-bootintegration-testing

解决方案


@RestTemplateTest给你预先配置RestTemplateBuilderMockRestServiceServer.

1.您可以@Autowired MockRestServiceServer模拟预期的 HTTP 调用。


2.删除自动配置:

@RestClientTest(excludeAutoConfiguration = MockRestServiceServerAutoConfiguration.class)

但这会使测试有点慢。也许有一种方法可以优化它。


3.另一方面,您可以删除@RestClientTest并在测试配置文件中创建一个RestTemplateBuilder. 像这样的东西:

@TestConfiguration
public class TestConfig {
    @Bean
    public RestTemplateBuilder getRestTemplateBuilder() {
        return new RestTemplateBuilder();
    }
}

在此之后,将此配置文件添加到您的导入中:

@Import(value = { TpzConfig.class, TpzServiceRestImpl.class, 
ManufacturingPlantPhPmMapperImpl.class, ProductHierarchyMapperImpl.class, 
PlantMapperImpl.class, TestConfig.class })

你应该对你的测试有好处。


推荐阅读