0
所以這裏的JUnit測試是我的函數:如何標題和文件添加到REST
@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();
}
我想使測試在JUnit中。但我不知道如何添加標題和文件。這是我的測試(它的工作原理):
@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));
}
但是我怎樣才能在這裏添加標題和文件? 標題我認爲我可以這樣做:request.addHeader(value, key);
還是我錯了?
而且我完全不知道如何添加文件到測試:/
頭對象可以使用了HTTPClient API。 –
標題通過request.addHeader添加。在你的測試中你創建了get請求,但這是一個PUT處理程序,所以你應該創建put請求來發送文件。可以使用http://stackoverflow.com/questions/11546609/use-httpclient-post-to-submit-form-with-upload中描述的方法發送文件 –