如何模拟rest API的http响应?

Rei*_*ica 5 api r http mocking testthat

我正在寻找在testthat框架内模拟其余 API 响应的最简单方法。

用法示例与此类似:

with_mock_api(
  request, 
  response, 
  {
      call_to_function_with_api_call()
      # expectations check
  }
)
Run Code Online (Sandbox Code Playgroud)

因此,测试将通过而不调用真正的 API。

  • request 指将在 api 包装函数内部完成的 http 请求的定义;
  • response 指为了模拟而缓存的响应对象。

sck*_*ott 4

https://github.com/ropensci/vcr使这变得非常简单。支持与crul以及 的集成httr

发出 API 请求的函数

foo_bar <- function() {
  x <- crul::HttpClient$new("https://httpbin.org")
  res <- x$get("get", query = list(foo = "bar"))
  jsonlite::fromJSON(res$parse("UTF-8"))
}
Run Code Online (Sandbox Code Playgroud)

然后运行块内的任何函数vcr::use_cassette,并像往常一样运行对输出期望的任何测试

library(testthat)
test_that("my_test", {
  vcr::use_cassette("foo_bar", {
    aa <- foo_bar()
  })

  expect_is(aa, "list")
  expect_named(aa, c("args", "headers", "origin", "url"))
  expect_equal(aa$args$foo, "bar")
})
Run Code Online (Sandbox Code Playgroud)

请求和响应存储在 yaml 文件中 -有关示例,请参阅https://github.com/ropensci/vcr#usage 。- 在第一次运行上述代码时,将发出真正的 HTTP 请求来创建该 yaml 文件,但在第二次以及之后的所有后续运行中,不会发出真正的 HTTP 请求,而是该函数使用该 yaml 文件。