首页 > 解决方案 > 无法在测试中通信 MultiPart/数据(Jersey/Junit)

问题描述

所以我在对解析 PDF 的方法进行单元测试时遇到了一些麻烦

@POST
@Consumes(MediaType.MULTIPART_FORM_DATA)
@Produces(MediaType.APPLICATION_JSON)
public Response parsingPdfOrange(@FormDataParam("fichier") InputStream uploadedInputStream,
        @FormDataParam("fichier") FormDataContentDisposition fileDetail) {

    try {

        String uploadedFileLocation = "D:/tmp/doc.pdf";

        String info = "facture Orange:"
                + OrangeService.ParseFacture(uploadedFileLocation, uploadedInputStream).toString();

        return Response.status(201).entity(info).build();

效果很好,我的网址给了我很好的结果等等,但是

    @Override
protected Application configure() {
    return new ResourceConfig(OrangeWebService.class).register(MultiPartFeature.class);

}

@Override
protected void configureClient(ClientConfig config) {
    config.register(MultiPartFeature.class);
}

@Test
public void parsePDF_NullPointerExcpetion() throws Exception {
    try {

        FileDataBodyPart filePart = new FileDataBodyPart("file", new File(pathtoRessources));
        FormDataMultiPart formDataMultipart = new FormDataMultiPart();
        FormDataMultiPart multipart = (FormDataMultiPart) formDataMultipart.bodyPart(filePart);

        Response response = (target("pdf").request().post(Entity.entity(multipart, multipart.getMediaType())));

        System.out.println(response);
        response.close();
    } catch (Exception e) {
        e.printStackTrace();
    }

这是我的测试代码,pb 在这里:看来我的 FormDataMultiPart 很好,但是当我执行 Entity.entity(multipart, multipart.getMediaType() 时,它会返回一个空值,因为我得到了一个 nullPointerException 。

我需要帮助,非常感谢。

标签: javamavenjunitjersey

解决方案


文件部分名称是"fichier"

@FormDataParam("fichier") InputStream uploadedInputStream

但是您将其发送为"file"

FileDataBodyPart filePart = new FileDataBodyPart("file", new File(pathtoRessources));

修复它。


推荐阅读