我希望使用ScalaJ-Http作为http客户端。链接:https://github.com/scalaj/scalaj-http
如何在单元测试中使用像下面这样的val response: HttpResponse[String] = Http("http://foo.com/search").param("q","monkeys").asString行代码模拟类的Http或HttpRequest
该类将从方法调用参数中获取url和params。所以我不能注射HttpRequest。
发布于 2017-08-12 04:54:02
我所做的是创建一个ScalajHttp包装类,如下所示:
import scalaj.http.{Http, HttpRequest}
/**
* This wraps the Scalaj Http object so it can be injected.
*/
class ScalajHttp {
def url(url: String): HttpRequest = Http(url)
}然后您可以轻松地将其注入到另一个类中:
class Foo(http: ScalajHttp) {
def doBar() = {
val response = http.url("http://...").asString
}
}然后,对于模拟,您可以使用类似于Specs2的东西,并创建ScalajHttp的模拟。
发布于 2017-02-27 18:54:11
很好奇你是否已经有了一个解决方案。我偶然发现你的帖子里也有同样的问题。
我最终解决了这个问题,只需使用Scalatra/Jetty在测试本身中创建一个“虚拟服务”,并在其中指定预期的响应。所以,这并不是真正的嘲笑,但它对我来说已经足够了。
这种方法的缺点是您必须包含Scalatra、Jetty-server和Jetty-servlet作为额外的依赖项(可以选择使用scope=test)。
def mockService: Server = {
class MockedServlet extends ScalatraServlet {
get("/") {
// fill in whatever you expect here
Ok("I'm alive!")
}
}
class ServletMounter extends LifeCycle {
override def init(context: ServletContext): Unit = {
context.mount(new MockedServlet, "/mock")
}
}
new Server(20002) {
val servlet = new ServletContextHandler(ServletContextHandler.NO_SESSIONS) {
addEventListener(new ScalatraListener() {
override def probeForCycleClass(classLoader: ClassLoader): (String, LifeCycle) = {
(classOf[ServletMounter].getSimpleName, new ServletMounter)
}
})
}
setHandler(servlet)
}
}
private val server = mockService
override protected def beforeAll(): Unit = {
super.beforeAll()
server.start()
}
override protected def afterAll(): Unit = {
server.stop()
server.destroy()
super.afterAll()
}
// a simple test
"service up" should "return a 200 when the mocked service is up" in {
val response = Http("http://localhost:20002/mock/").asString
response.code shouldBe 200
response.body shouldBe "I'm alive!"
}编辑2017年3月2日:经过一番考虑后,我更改了代码,以便在“外观”特征中通过scalaj-http进行HTTP调用,以便能够在测试中模拟。现在,我模拟外观并返回预期的HTTPResponse,而不是执行实际的HTTP请求。与上面显示的解决方案相比,这要清晰得多,上面提到的依赖关系不再是必要的,设置也更容易。外观可以作为构造函数参数或自类型注释“注入”到执行HTTP调用的类中。
https://stackoverflow.com/questions/41963568
复制相似问题