如何测试在Kotlin中调用顶层函数的代码?

我对Kotlin很新。

我有一个类调用顶级功能(这使得一个http调用)。 我正在尝试为我的课程编写单元测试,而不必将其发布到网络上。

有没有办法模拟/ powermock /拦截从我的课到Kotlin顶级功能的呼叫?

class MyClass { fun someMethod() { // do some stuff "http://somedomain.com/some-rest/action".httpGet(asList("someKey" to "someValue")).responseString { (request, response, result) -> // some processing code } } } 

它使用kittinunf / Fuel库进行httpGet调用。

它将一个顶级函数添加到String中,最终在Fuel(Fuel.get())中调用伴随对象函数。

单元测试需要拦截对httpGet的调用,以便我可以返回测试的json字符串。

我鼓励你将远程API调用封装在一个接口之后,这个接口将通过构造函数注入到使用它的类中:

 class ResponseDto interface SomeRest { fun action(data:Map<String,Any?>): ((ResponseDto)->Unit)->Unit } class FuelTests(val someRest: SomeRest) { fun callHttp(){ someRest.action(mapOf("question" to "answer")).invoke { it:ResponseDto -> // do something with response } } } 

另一种方法是注入一个假的ClientFuel

 FuelManager.instance.client = object: Client { override fun executeRequest(request: Request): Response { return Response().apply { url = request.url httpStatusCode = 201 } } } Fuel.testMode() "http://somedomain.com/some-rest/action".httpGet(listOf()).responseString { request, response, result -> print(response.httpStatusCode) // prints 201 } 

看来“顶级职能”可以被看作是变相的静态方法。

从这个角度来看,更好的答案是:不要以这种方式使用它们。 这导致高度,直接的耦合; 并使你的代码更难测试。 你一定要创建一个接口服务 ,你的所有对象应该使用; 然后使用依赖注入为您的客户端代码提供一些实现Service接口的对象。

通过这样做,你也完全摆脱了Powermock的要求。