我们正在慢慢地将一些项目从使用遗留的RestTemplate类迁移到新的Spring5 WebClient。作为其中的一部分,我们有一些现有的测试类,它们利用Mockito来验证给定的方法是否会使用模板向端点X发出GET/POST/任何东西。
考虑到WebClient的流畅接口,同样的模拟方法并不实际。我花了一些时间使用WireMock,这很好,但不幸的是,似乎有一个bug,有时WireMock测试会溢出或挂起,因此我正在考虑替代方案。
有没有人对框架或技术有其他建议,可以用来验证Spring的WebClient作为SUT执行的一部分是否进行了预期的调用?
发布于 2018-06-20 22:25:19
Spring实际上使用OkHttp MockWebServer来测试WebClient。
Spring's Example Integration Tests
您可以设置有序的模拟响应或将模拟响应映射到请求详细信息。
发布于 2021-08-18 09:45:33
MockWebServer听起来像是一个很酷的方法。一个适用的示例是:
@ExtendWith(MockitoExtension.class)
class serviceImplTest {
private ServiceImpl serviceImpl;
public static MockWebServer mockWebServer;
@BeforeAll
static void setUp() throws IOException {
mockWebServer = new MockWebServer();
mockWebServer.start();
}
@AfterAll
static void tearDown() throws IOException {
mockWebServer.shutdown();
}
@BeforeEach
void init() {
String baseUrl = String.format("http://localhost:%s", mockWebServer.getPort());
serviceImpl = new ServiceImpl(WebClient.builder(), baseUrl);
}
@Test
@DisplayName("whatever")
void methodName() {
mockWebServer.enqueue(new MockResponse().addHeader("header", "abcde123")); //MockWebServer will respond with the queued stub.
String header = serviceImpl.fetchHeader();
assertThat(header).isEqualTo("abcde123");
}
}https://stackoverflow.com/questions/50575922
复制相似问题