【问题标题】:How to mock http response of rest API?如何模拟rest API的http响应?
【发布时间】:2020-02-04 05:55:42
【问题描述】:

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

用法示例与此类似:

with_mock_api(
  request, 
  response, 
  {
      call_to_function_with_api_call()
      # expectations check
  }
)

因此,无需调用真正的 API 即可通过测试。

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

【问题讨论】:

  • 例如,request 和 response 是什么?

标签: r api http mocking testthat


【解决方案1】:

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"))
}

然后在 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")
})

请求和响应存储在 yaml 文件中 - 参见 https://github.com/ropensci/vcr#usage 示例。 - 在上面代码的第 1 次运行中,将发出一个真正的 HTTP 请求来生成该 yaml 文件,但在第 2 次和之后的所有后续运行中,没有发出真正的 HTTP 请求,而是该函数使用该 yaml 文件。

【讨论】:

    【解决方案2】:

    还有httptest 包为R 中的http 请求提供模拟功能。

    在您的测试中添加 with_mock_api() 很简单。如果我们将代码包装在 with_mock_api() 中,则不会发生实际请求。

    with_mock_api({
        test_that("Requests happen", {
            expect_s3_class(GET("http://httpbin.org/get"), "response")
            expect_s3_class(
                GET("http://httpbin.org/response-headers",
                    query=list(`Content-Type`="application/json")),
                "response"
            )
        })
    })
    

    【讨论】:

      猜你喜欢
      • 2017-10-09
      • 2023-02-07
      • 2018-04-21
      • 2015-05-03
      • 1970-01-01
      • 2019-07-07
      • 1970-01-01
      • 2014-09-01
      • 2021-05-14
      相关资源
      最近更新 更多