首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >由于ResourceConfig不需要参数构造函数,Dropwizard文件上传测试失败

由于ResourceConfig不需要参数构造函数,Dropwizard文件上传测试失败
EN

Stack Overflow用户
提问于 2016-04-07 22:43:04
回答 1查看 773关注 0票数 1

我在Dropwizard中实现了一个文件上传REST端点。我是新来的,我只是试着学习。

代码语言:javascript
复制
@Path("/files")
@Produces(MediaType.APPLICATION_JSON)
public class FileUploadResource {

    private final MyAppWebConfiguration configuration;
    private static final Logger logger = LoggerFactory.getLogger(FileUploadResource.class);

    public FileUploadResource(MyAppWebConfiguration configuration) {
        this.configuration = configuration;
    }

    @POST
    @Consumes(MediaType.MULTIPART_FORM_DATA)
    public Response uploadFile(
            @FormDataParam("file") InputStream uploadedInputStream,
            @FormDataParam("file") FormDataContentDisposition fileDetail) throws IOException {

        logger.info("Request to upload the file ", fileDetail.getFileName());
        final String uploadedFileLocation = configuration.getCsvUploadPath();
        final String fileName = fileDetail.getFileName();
        writeToFile(uploadedInputStream, uploadedFileLocation, fileName);
        return Response.ok("File " + fileName + " is uploaded to the location " + uploadedFileLocation).build();
    }

    // save uploaded file to new location
    protected void writeToFile(InputStream uploadedInputStream, String uploadedFileLocation, String fileName) throws IOException {
        logger.info("Writing {} to {}", fileName, uploadedFileLocation);
        final java.nio.file.Path outputPath = FileSystems.getDefault().getPath(uploadedFileLocation, fileName);
        Files.copy(uploadedInputStream, outputPath, StandardCopyOption.REPLACE_EXISTING);
        logger.info("Uploaded {} to the location {}", fileName, uploadedFileLocation);
    }

代码工作正常,能够上传文件。我正在尝试使用以下基于https://gist.github.com/psamsotha/218c6bbeb6164bac7cbc的代码来测试它:

代码语言:javascript
复制
public class FileUploadResourceTest extends JerseyTest {

    private final static MyAppWebConfiguration mockConfiguration = mock(MyAppWebConfiguration.class);

    @Override
    public ResourceConfig configure() {
        return new ResourceConfig(FileUploadResource.class)
                .register(MultiPartFeature.class)
                .register(new LoggingFilter(Logger.getAnonymousLogger(), true));
    }

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

    @Test
    public void test() {
        FileDataBodyPart filePart = new FileDataBodyPart("file", new File("/Users/rocky/Downloads/test.csv"));
        filePart.setContentDisposition(FormDataContentDisposition.name("file").fileName("/Users/rocky/Downloads/test.csv").build());

        MultiPart multiPart = new FormDataMultiPart()
                .bodyPart(filePart);
        Response response = target("/files").request()
                .post(Entity.entity(multiPart, MediaType.MULTIPART_FORM_DATA_TYPE));
        assertThat(response.getStatus()).isEqualTo(Response.Status.OK.getStatusCode());
        response.close();
    }

此测试失败,出现以下错误:

代码语言:javascript
复制
WARNING: The following warnings have been detected: WARNING: HK2 service reification failed for [com.my.app.resources.FileUploadResource] with an exception:
MultiException stack 1 of 2
java.lang.NoSuchMethodException: Could not find a suitable constructor in com.my.app.resources.FileUploadResource class.
    at org.glassfish.jersey.internal.inject.JerseyClassAnalyzer.getConstructor(JerseyClassAnalyzer.java:192)
    at org.jvnet.hk2.internal.Utilities.getConstructor(Utilities.java:178)
    at org.jvnet.hk2.internal.ClazzCreator.initialize(ClazzCreator.java:128)
    at org.jvnet.hk2.internal.ClazzCreator.initialize(ClazzCreator.java:179)

我在FileUploadResource中没有任何参数构造函数,但是new ResourceConfig(FileUploadResource.class)需要一个无参数构造函数。如何在这里传递关于一个参数构造函数的信息?

这里的任何帮助都将是非常感谢的。此外,请随时建议关于代码和测试的任何其他最佳实践,以便我能够改进它们。

在此之前,非常感谢您。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2016-04-07 23:24:43

将资源注册为类时

代码语言:javascript
复制
new ResourceConfig(FileUploadResource.class)

你是在告诉泽西去创造它。但是它不知道如何创建它,因为只有一个构造函数可以接受配置对象,而泽西岛对此一无所知。相反,您应该注册为一个对象。与注册Dropwizard (env.jersey().register(...))的方式相同。

代码语言:javascript
复制
new ResourceConfig().regster(new FileUploadResource(mockConfiguration))
    ...

顺便提一下,对于Dropwizard,我们不需要显式地使用JerseyTest。Dropwizard附带了一个JUnit规则,它显式地运行自己的JerseyTest,我们可以使用该规则配置它。参见本期,在这里我发布了一个完整的示例。

票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/36488512

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档