0

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.

KAY_YAK
  • 191
  • 10

1 Answers1

-1

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.

ultrasecr.eth
  • 1,437
  • 10
  • 13
  • Any articles on wiremock and how to set up an URL with a file to download? – KAY_YAK Apr 18 '19 at 12:47
  • First example here should do the trick http://wiremock.org/docs/request-matching/ if you really wanna simulate a file download, altough for what I can see in your example it seems you just get the response body and save it to a file... if that's the case then the most simple example from http://wiremock.org/docs/stubbing/ should do the trick – ultrasecr.eth Apr 18 '19 at 12:56
  • `stubFor(get("/somefile.csv").willReturn(??)` I am confused about what to put here. I read from the file as input stream and pass the input stream there? – KAY_YAK Apr 18 '19 at 13:10
  • The question is what you expect as a user of that REST API, cause that's what you have to simulate for your system, then you worry how to do that. So, does your system actually download a file from the server or it just gets the body from a standard HTTP response and then write that in a file? – ultrasecr.eth Apr 18 '19 at 17:04