使用@requestbody测试端点的单元



,所以当我的http响应代码为200时,我的http响应代码得到了400。内容类型正确?有什么建议吗?

@RequestMapping(value = "/test", method = RequestMethod.POST, consumes = "application/octet-stream")
      public ResponseEntity<String> receiveCompressedBinary(@RequestHeader String site, @RequestHeader String customer,
          @RequestHeader String table, @RequestBody byte[] binary, @RequestHeader String loadStatus) {
        if(binary.length < maxFileSize) {
            return new ResponseEntity<String>(HttpStatus.OK);
        }
        else{
          return new ResponseEntity<String>(HttpStatus.PAYLOAD_TOO_LARGE);
        }
      }

我的测试:

@Test
  public void testUploadCompressedBinaryInitialRunning() throws Exception{
    File file = new File("src/test/resources/testFile.txt");
    String site = "site";
    String customer = "customer";
    String table = "table";
    String loadStatus = "INITIALRUNNING";
    this.mockMvc.perform(post("/test").header("site",site).param("customer",customer).
        param("table", table).content(compress(file)).param("loadStatus",loadStatus)
        .with(user("user"))).andExpect(status().isOk());
   this.mockMvc.perform(post("/uploadCompressedBinary")).andDo(print()).andExpect(status().isOk());
  }

压缩方法:

 public static byte[] compress(File file) throws IOException {
    if (file.length() == 0) {
      return null;
    }
    FileInputStream fileInputStream = null;
    byte[] fileInBytes = new byte[(int)file.length()];
    try {
      //convert file into array of bytes
      fileInputStream = new FileInputStream(file);
      fileInputStream.read(fileInBytes);
      fileInputStream.close();
    } catch (IOException e) {
      System.out.println("Exception whilst compressing the file: " + e.getMessage());
    }
    ByteArrayOutputStream obj = new ByteArrayOutputStream();
    GZIPOutputStream gzip = new GZIPOutputStream(obj);
    gzip.write(fileInBytes);
    gzip.close();
    return obj.toByteArray();
  }

更新:超越了它,而不是.param,我应该使用.header

在发布时看起来并不是您正在设置内容类型。

尝试

this.mockMvc.perform(post("/test").header("site",site).param("customer",customer).
        param("table", table).content(compress(file)).contentType("application/octet-stream").param("loadStatus",loadStatus)
        .with(user("user"))).andExpect(status().isOk());

相关内容

  • 没有找到相关文章

最新更新