简体   繁体   English

如何使用 Java 和 Spark 模拟多部分/表单数据?

[英]How to mock multipart/form-data with Java and Spark?

I'm receiving a file using multipart/form-data like I'll show you right below (Using Spark, not SpringBoot):我正在接收一个使用 multipart/form-data 的文件,就像我将在下面向您展示(使用 Spark,而不是 SpringBoot):

 @Override
public Object handle(Request request, Response response) throws Exception {
    request.attribute("org.eclipse.jetty.multipartConfig", new MultipartConfigElement(""));

    Part filePart = request.raw().getPart("file");
    String regex = request.raw().getParameter("regex");
    String fileName = filePart.getSubmittedFileName();
    byte[] fileBytes = filePart.getInputStream().readAllBytes();

The thing is, I want to unit test this Controller, and in order to do so, I need a way to mock the request to have a multipart/form-data inside, or at least a way to use "when...theReturn" to mimic that part of code... Any ideas?问题是,我想对这个控制器进行单元测试,为此,我需要一种方法来模拟请求以在其中包含多部分/表单数据,或者至少是一种使用“when...theReturn”的方法“模仿那部分代码......有什么想法吗?

Thanks in advance!提前致谢!

So I managed to find the answer to this question and I thought maybe I could help other people by answering it:所以我设法找到了这个问题的答案,我想也许我可以通过回答来帮助其他人:

@Test
public void whenValidRegex_returnOkAndTotalAmount() throws Exception {
    final Part file = mock(MultiPartInputStreamParser.MultiPart.class);
    final Request mock = mock(Request.class); //Spark request
    final Response mockResponse = mock(Response.class); //Spark response
    final HttpServletRequest httpServletRequest = mock(HttpServletRequest.class); //Javax servlet

    when(mock.raw()).thenReturn(httpServletRequest);
    when(file.getSubmittedFileName()).thenReturn("file.pdf");
    when(mock.raw().getParameter("regex")).thenReturn(String.valueOf("SOME REGEX"));
    when(mock.params("numPage")).thenReturn(String.valueOf("1"));
    when(file.getInputStream()).thenReturn(IOUtils.toInputStream("ARGENTINIAN PESOS", Charset.defaultCharset())); //Here you are mocking the input stream you might get from the part file.
    when(mock.raw().getPart("file")).thenReturn(file);

Now that you have the multipart/form-data mocked, you can continue your test mocking the service calls and such things.现在您已经模拟了 multipart/form-data,您可以继续模拟服务调用等内容的测试。 Please ignore things that are from my specific code, like the "Page number" mocking, you don't need that.请忽略我的特定代码中的内容,例如“页码”模拟,您不需要它。 Hope this helps for someone else.希望这对其他人有帮助。 Bye!再见!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM