0

I've seen a lot of examples on how to mock a connection in Java but haven't seen any explaining how to do it in Kotlin. A bit of code that I want mocked as an example:

val url = URL("https://google.ca")
val conn = url.openConnection() as HttpURLConnection

with(conn) {
    //doStuff
}
conn.disconnect()

Similar to a question like this but for Kotlin: how to mock a URL connection

Alex
  • 419
  • 6
  • 24
  • why would it be any different – Tim Dec 10 '19 at 16:53
  • 1
    You shouldn't mock that in the first place. With mocking, a passing test won't give you any idea if your code is actually correct and can correctly interact with an HTTP server. Instead, use something like okhttp's mock http server, and use your real code to connect to that server (by injecting the mock server's url rather than the real URL) https://github.com/square/okhttp/tree/master/mockwebserver – JB Nizet Dec 10 '19 at 16:54

1 Answers1

0

Kotlin and Java can interop with one another, so you should be able to take your exact example (from the question) provided and convert it to Kotlin (or don't convert it and call the Java directly):

@Throws(Exception::class)
fun function() {
        val r = RuleEngineUtil()
        val u = PowerMockito.mock(URL::class.java)
        val url = "http://www.sdsgle.com"
        PowerMockito.whenNew(URL::class.java).withArguments(url).thenReturn(u)
        val huc = PowerMockito.mock(HttpURLConnection::class.java)
        PowerMockito.`when`(u.openConnection()).thenReturn(huc)
        PowerMockito.`when`(huc.getResponseCode()).thenReturn(200)
        assertTrue(r.isUrlAccessible(url))
}

It's worth noting that you should probably consider using an actual mocking HTTP server like HttpMocker for handling this as opposed to implement the behavior yourself.

Rion Williams
  • 74,820
  • 37
  • 200
  • 327