0

I want to test this Controller in postman:

@PostMapping(value = "/create")
    public ResponseEntity<Map<String, Object>> create(
            @RequestParam(name = "avatar", required = false) MultipartFile file, @RequestParam("data") String data,
            HttpServletRequest request) throws Exception {
                Document obj = documentService.create(data, file);
        Map<String, Object> uploadObj = new HashMap<String, Object>();
        if (!obj.equals(null)) {
            uploadObj.put("objection", obj);
            return ResponseEntity.ok(uploadObj);
        }

        return null;
    }

my documentService implementation code is like this:

 public Document create(String data, MultipartFile file) {
        try {

            JsonNode root = mapper.readTree(data);
            Document document = new Document();

            document.setTitle(root.get("title").asText());
            document.setBody(root.get("body").asText());
            document.setNumber(root.get("number").asText());
            Document newObj = repo.save(document);
 String fileName = fileUploadUtil.saveAttachment(file, uploadDir, newObj.getId().toString(), "document");
            if (newObj != null) {
                newObj.setFileName(fileName);
                return repo.save(newObj);
            }
            return null;
}

and saveAttachment method save my file which have another implementation now I want to test with postman how should I test it??? I tried the following in postman at body>raw>json and use file in form-data as a file but no work!.

{
    "data":[
        {
            "number":987,
            "body":"body is the best part",
            "title":"title is so important part"
        }
    ]
}

can anyone help me how to test it????

abdul wahid
  • 111
  • 2
  • 10

1 Answers1

1

Your controller method is currently expecting two request parameters, not a request body for the data. Try this in postman: enter image description here

Another option is to change the controller method to accept the request body for the data class, you should also write a class representing your data object and not accept the json as a string:

@PostMapping(value = "/create")
public ResponseEntity<Map<String, Object>> create(
        @RequestParam(name = "avatar", required = false) MultipartFile file,
        @RequestBody MyDataObj data,
        HttpServletRequest request
) throws Exception {
void void
  • 1,080
  • 3
  • 8