Spring 6.1 RestClient JUnit 模拟测试

问题描述 投票:0回答:1

我有一个 Spring 6.1 RestClient:

@Service
@RequiredArgsConstructor
public class ProductServiceClient {

  @Value("${spring.client.product.url}")
  private final String baseUrl;

  private final RestClient restClient;

  public List<ProductPriceDto> getProductPrices(UUID productId, LocalDate date) {
    String url = baseUrl + "/products/" + productId + "/prices/?date=" + date;

    return restClient.get().uri(url).retrieve().body(new ParameterizedTypeReference<>() {});
  }
}

以及 Spring 配置:

@Configuration
public class RestClientConfig {

  @Bean
  public RestClient restClient() {
    return RestClient.create();
  }

}

现在我想要一个 JUnit5 测试来模拟这个客户端。有人可以给我一个样品吗?由于这个客户端也是从其他测试中调用的,我也想知道如何在那里模拟它=?

spring spring-boot mocking junit5 rest-client
1个回答
0
投票

我用 okhttp3.mockwebserver.MockWebServer 解决了我的问题

@SpringBootTest
class ProductServiceClientTest {
 private MockWebServer mockWebServer;
 private ProductServiceClient productServiceClient;

  @BeforeEach
  void setUp() throws IOException {
    mockWebServer = new MockWebServer();
    mockWebServer.start();
    // Configure the RestClient to point to the MockWebServer URL
    RestClient restClient = RestClient.builder().baseUrl(mockWebServer.url("/").toString()).build();
    // Configure the ProductServiceClient to use the mocked vales
    productServiceClient = new ProductServiceClient(mockWebServer.url("/").toString(), restClient);
  }

  @AfterEach
  void tearDown() throws IOException {
    mockWebServer.shutdown();
  }

  @Test
  void testGetProductPrices() throws Exception {
    UUID productId = UUID.randomUUID();
    LocalDate date = LocalDate.now();

    var expectedResponse =
        List.of(
            new ProductPriceDto(date, 49L, 500), new ProductPriceDto(date.plusDays(1), 39L, 700));
    ObjectMapper mapper = new ObjectMapper();
    mapper.registerModule(new JavaTimeModule());
    String jsonResponse = mapper.writeValueAsString(expectedResponse);

    mockWebServer.enqueue(
        new MockResponse()
            .setBody(jsonResponse)
            .addHeader("Content-Type", MediaType.APPLICATION_JSON_VALUE));

    List<ProductPriceDto> actualResponse = productServiceClient.getProductPrices(productId, date);

    assertEquals(expectedResponse, actualResponse);
  }
}
© www.soinside.com 2019 - 2024. All rights reserved.