spring-boot - 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 的地方)?
解决方案
@RestTemplateTest
给你预先配置RestTemplateBuilder
和MockRestServiceServer
.
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 })
你应该对你的测试有好处。
推荐阅读
- android - 蓝牙 Gatt 服务器 Android 设备 Null
- pandas - 使用多元素计算的交叉表
- python - 破折号不刷新页面
- apache-samza - 应用部署在yarn中时samza如何生成container.id?
- flutter - 颤振未处理的异常:类型'_InternalLinkedHashMap
' 不是类型 'List 的子类型 ' - html - 如何在 html 文件中粘贴值,该值作为字典从 Django 传递到 html,如果我使用“{{}}”,则该值将粘贴到模板中
- terraform - 通过 terraform 管理 Auto Scaling 组
- python - Django 相关模型未在表单提交时更新
- kotlin - 如何使用 Kotlin 序列化为嵌套 JSON 组合多态和转换序列化器?
- azure - Azure Boards,如何使用每个工作项类型?