1
@RestController
@CrossOrigin
public class KycController {
org.slf4j.Logger log = org.slf4j.LoggerFactory.getLogger(KycController.class);
    @Autowired
    private KycRepo repo;

    @Autowired
    private KycService kycService;

    @Value("${kyc.basePath}")
    private String basePath;
    
    @PostMapping("/ekyc")
    public ResponseEntity<Object> insert( @Valid @ModelAttribute KycEntity entity, BindingResult bindingResult) {
        
        
//      try {
//          entity.getImageFile().getBytes();
//      } catch (IOException e) {
//             log.error("Error while getting image bytes: {}", e);
//      }
        System.out.println(entity.getFirstName());
        System.out.println(bindingResult.hasErrors());
        if (bindingResult.hasErrors()) {
            // Convert validation errors to a more readable format
            List<String> errors = bindingResult.getAllErrors().stream()
                .map(error -> error.getDefaultMessage())
                .collect(Collectors.toList());
            System.out.println(errors);
            return new ResponseEntity<>(errors, HttpStatus.BAD_REQUEST);
        }

        try {
            if (!entity.getImageFile().isEmpty()) {
                
                // Generate a unique filename using a timestamp or UUID
                String uniqueFilename = UUID.randomUUID().toString() + ".jpg";
                
                // Combine the base path and unique filename to get the complete image path
                String imagePath = Paths.get(basePath, uniqueFilename).toString();
                
                // Get the byte array representing the uploaded image
                byte[] imageBytes = entity.getImageFile().getBytes();
                
                // Save the image to the specified path
                Files.write(Paths.get(imagePath), imageBytes);
                
                // Set the image path in the entity
                entity.setImage(imagePath);
                
                // You can now save the entity to your database
                KycEntity savedEntity = repo.save(entity);

                if (savedEntity != null) {
                    return new ResponseEntity<>("Insert successful", HttpStatus.OK);
                } else {
                    return new ResponseEntity<>("Insert failed", HttpStatus.INTERNAL_SERVER_ERROR);
                }
            } else {
                return new ResponseEntity<>("Image file is empty", HttpStatus.BAD_REQUEST);
            }
        } catch (Exception e) {
            return new ResponseEntity<>("Insert failed: " + e, HttpStatus.INTERNAL_SERVER_ERROR);
        }
    }
This was api and 

class EkycControllerTest {

    @Autowired
    private MockMvc mockMvc;

    @InjectMocks
    private KycController controller;

    @Mock
    private KycEntity entity;

    @Mock
    private KycService kycService; // Mock the service

    @BeforeEach
    public void setUp() {
        MockitoAnnotations.initMocks(this);
        mockMvc = MockMvcBuilders.standaloneSetup(controller).build();
        // Perform any setup if needed before running the tests.
    }

    @Test
    void testInsertApiWithValidData() throws Exception {
        // Create a MockMultipartFile for image data
        MockMultipartFile imageFile = new MockMultipartFile("imageFile", "image.jpg", MediaType.IMAGE_JPEG_VALUE,
                "image content".getBytes());

        // Create a KycEntity with the necessary properties
        KycEntity entity = new KycEntity();
        entity.setFirstName("John");
        entity.setMiddleName("Doe");
        entity.setLastName("Smith");
        entity.setEmail("[email protected]");
        entity.setState("State");
        entity.setCity("City");
        entity.setNum("1234567890");
        entity.setAdd("123 Main St");
        entity.setAdd2("Apt 2B");
        entity.setPincode("123456");
        entity.setImage("image_url.jpg");
//      entity.setImageFile(imageFile);
        entity.setImageByte(imageFile.getBytes());

//      when(entity.getImageFile()).thenReturn(imageFile);
        ObjectMapper objectMapper = new ObjectMapper();
        String entityJson = objectMapper.writeValueAsString(entity);
        System.out.println(entityJson);
//      MockMultipartFile jsonfile = new MockMultipartFile("json", "", "application/json", entity.getbytes());
        mockMvc.perform(MockMvcRequestBuilders.post("/ekyc")
//              .file("entity", entityJson.getBytes())
                .contentType(MediaType.APPLICATION_JSON)
                .content(new ObjectMapper().writeValueAsString(entity)))
                .andExpect(MockMvcResultMatchers.status().isOk())
                .andExpect(MockMvcResultMatchers.content().contentType(MediaType.APPLICATION_JSON));
//      mockMvc.perform(MockMvcRequestBuilders.multipart("/ekyc").file(imageFile)
//              .contentType(MediaType.APPLICATION_JSON).content(new ObjectMapper().writeValueAsString(entity)))
//              .andExpect(MockMvcResultMatchers.status().isOk())
//              .andExpect(MockMvcResultMatchers.content().contentType(MediaType.APPLICATION_JSON));
    }

**This test case fails and also the i am not getting the mock data to the frontend side **

Console output {"kycId":0,"firstName":"John","middleName":"Doe","lastName":"Smith","email":"[email protected]","state":"State","city":"City","num":"1234567890","add":"123 Main St","add2":"Apt 2B","pincode":"123456","image":"image_url.jpg","imageFile":null,"imageByte":"aW1hZ2UgY29udGVudA=="} null true [must not be null, State is required, must not be null, Address is required, Pincode is required, must not be null, must not be null, Num is required, Last name is required, must not be null, City is required, must not be null, Address is required, must not be null, must not be null, Middle name is required, First name is required, Image URL is required, must not be null, must not be null, must not be null]

To make this api i have made the multipart file field in the entity so in this entity i have whole data required from user but now i can not able to also convert that multipart data in to json string using object mapper. Please also give the ans of it also

1 Answer 1

0

When we use the @ModelAttribute In the Api Side in the Spring Boot then To pass the Mock data from the Test cases while using mockmvc you need to pass .param("var name","data")
Like this mockMvc.perform(MockMvcRequestBuilders.multipart("/ekyc") .file(imageFile) .param("firstName", "John") .param("middleName", "Doe") .param("lastName", "Smith") .param("email", "[email protected]") .param("state", "California") .param("city", "Los Angeles") .param("num", "1234567890") .param("add", "123 Main St") .param("add2", "Apt 123") .param("pincode", "90001") .param("image", "Xyz.jpg")) .andExpect(MockMvcResultMatchers.status().isOk());

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.