0

So here is my function:

@POST
@Path("/upload")
@Consumes(MediaType.MULTIPART_FORM_DATA)
public Response postMsg(@HeaderParam("FTP-Host") String Host, @HeaderParam("FTP-Port") String Port,
        @HeaderParam("FTP-User") String User, @HeaderParam("FTP-Password") String Password,
        @HeaderParam("FTP-Path") String Path, @FormDataParam("file") InputStream inputStream) {

    try {
        InformationHandler informationHandler = new InformationHandler(Path, Host, Port, User, Password);

        CountriesStructure worker = new CountriesStructure();
        worker.prepareCountriesStructure(inputStream, true, informationHandler);

    } catch (UsernameOrPasswordException e) {
        e.printStackTrace();
        return Response.status(401).entity("Status 401.").build();
    } catch (SocketException e) {
        e.printStackTrace();
        return Response.status(404).entity("Status 404.").build();
    } catch (IOException e) {
        e.printStackTrace();
        return Response.status(400).entity("Status 400.").build();
    } catch (JAXBException e) {
        e.printStackTrace();
        return Response.status(500).entity("Status 500.").build();
    } catch (Exception e) {
        e.printStackTrace();
        return Response.status(500).entity("Status 500.").build();

    }
    return Response.status(200).entity("Success!").build();
}

And I want to make test in Junit. But I don't have idea how to add headers and file. Here is my test (it works):

@Test
public void firstTest()
        throws ClientProtocolException, IOException {
    HttpUriRequest request = new HttpGet("http://localhost:8080/JerseyWebApp/ftpaction/upload");
    HttpResponse httpResponse = HttpClientBuilder.create().build().execute(request);
    assertThat(httpResponse.getStatusLine().getStatusCode(), equalTo(HttpStatus.SC_METHOD_NOT_ALLOWED));
}

But how can I add here headers and file? Header I think that I can do in that way: request.addHeader(value, key); or am I wrong?

And I have totally no idea how to add file to test :/

Marek S
  • 109
  • 2
  • 10
  • You can use HTTPClient API. – Rahul Yadav Sep 09 '15 at 11:17
  • 1
    Headers are added via request.addHeader. In your test you create get request but this is a PUT handler so you should create put request to be able to send files. File can be sent using method described in http://stackoverflow.com/questions/11546609/use-httpclient-post-to-submit-form-with-upload – Roman-Stop RU aggression in UA Sep 09 '15 at 11:27

1 Answers1

1

You need to mock Header object using Mockito or other frameworks

MockHttpServletRequest request = new MockHttpServletRequest();
request.addHeader("x-real-ip","127.0.0.1");
HaveNoDisplayName
  • 8,291
  • 106
  • 37
  • 47
Ram
  • 55
  • 5