class HttpUtils{
def get(userId: String, organization: String, url: String) =
{
Logger.debug("Request - GET :: " + url)
val wsClient = AhcWSClient()
wsClient.url(url).withHttpHeaders("userId"-> userId,"organization"-> organization).get()
.andThen { case _ => wsClient.close() }
.andThen { case _ => system.terminate() }
}
}
class MetamodelClient @Inject()(httpUtils:HttpUtils)(隐式defaultExecutionContext:ExecutionContext){
隐式val格式= org.json4s.DefaultFormats
def getDBDetails(userId:String,organization:String,metamodelUrl:String,model:String)= { httpUtils.get(userId,organization,metamodelUrl +" / models /" + model +" / modelsets")。map { resp => resp.status match { case Status.OK =>解析(resp.body).extract [列表[DatabaseDetails]] case _ =>的HandleError(resp.status) } } } }
无法为getDBDetails方法编写测试用例程序。任何人都可以帮助我。
答案 0 :(得分:2)
您应该考虑为什么要为此代码编写测试,这将有助于指导您如何。
参见例如https://dzone.com/articles/top-8-benefits-of-unit-testing
这里有很多问题让我们难以测试:
get()
" get
调用是正确的,但是如果不连接到远程API并尝试它,就无法测试它是否符合您的要求。这超出了单元测试的范围。AhcWSClient
我会考虑注入一个WS客户端工厂来修复(4)。
我会考虑重构你的关闭过程,将它与应用程序逻辑分开,以修复(3)。
我不会测试这段代码,因为(1)& (2)。没有办法通过单元测试验证它是否正确。
如果您确实坚持对此进行测试,可能是因为您对您实施了不灵活的100%覆盖率政策,我会做更多的事情:
class SomethingFetcher(clientFactory: () => AhcWSClient, somethingApiUrl: String) {
def get(userId: String, organization: String): Something = {
val wsClient = AhcWSClient()
wsClient.url(url).withHttpHeaders("userId"-> userId,"organization"-> organization).get()
.andThen { case _ => wsClient.close() }
}
}
...
class SomethingFetcherSpec {
"SomethingFetcher" should "invoke GET on the specified URL" in {
// arrange
val mockWsClient = ... // this will be a bit fiddly
val wsClientFactory = () => mockWsClient
val fetcher = SomethingFetcher(wsClientFactory, "http://example.com/something")
// act
val ignored = fetcher.get("test uid", "test oid")
// assert
verify(mockWsClient).get("http://example.com/something")
}
}