I have a function that makes a request gets the response in bytes and writes to file. A part of the function is given below.
val bytes = Http(url).timeout(connTimeout, readTimeout).method("GET").proxy(proxyUrl, proxyPort).asBytes.body
val dest = new File(filePath)
dest.createNewFile
val out = new FileOutputStream(destFile)
IOUtils.write(bytes, out)
IOUtils.closeQuitely(out)
I am trying to unit test this function. I am using mockito
and Http
is an Object. So, mocking it not possible. But on the other hand HttpRequest
and HttpResponse
are case
classes and can be mocked. So, I did this in the test.
//Read bytes from test resource file
val bytes = Files.readAllBytes(Paths.get(testFile))
// Mock
val mockHttpReq = mock(classOf[HttpRequest])
val mocmHttpRes = mock(classOf[HttpResponse[Array[Byte]])
when(mockHttpReq.asBytes).thenReturn(mockHttpRes)
when(mockHttpRes.body).thenReturn(bytes)
Now when I call the actual function i.e. when
Http(url).timeout(connTimeout, readTimeout).method("GET").proxy(proxyUrl, proxyPort).asBytes.body
is actually called I dont get any Byte
i.e. its empty.
I am new to scala and mockito. I think I set everything correctly. If I am missing anything please guide me.
I think you are not using the right tool for the job, mocks are mainly intended to mock your own classes, you should try to avoid as much as possible to mock third party APIs/classes.
For this particular problem, what I'd recommend is to do an integration test for this component (let's call it
MyHttpClient
), using something like wiremock as your fake webserver.Once you have
MyHttpClient
tested, then you are free to mock it in any other test where the component you're testing depends on it.