如何使用mockmvc将实体json和多部分文件发送到json数据

问题描述 投票:0回答: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));
    }

**这个测试用例失败了,而且我没有将模拟数据发送到前端**

控制台输出 {"kycId":0,"firstName":"John","middleName":"Doe","lastName":"Smith","email":"[电子邮件受保护]","state":"州","city":"城市","num":"1234567890","add":"123 Main St","add2":"Apt 2B","pincode":"123456","image":" image_url.jpg","imageFile":null,"imageByte":"aW1hZ2UgY29udGVudA=="} 无效的 真的 [不得为空,州为必填项,不得为空,地址为必填项,Pincode 为必填项,不得为空,不得为空,Num 为必填项,姓氏为必填项,不得为空,城市为必填项,不得为空,地址为必填项,不得为空,不得为空,中间名为必填项,名字为必填项,图像 URL 为必填项,不得为空,不得为空,不得为空]

为了制作这个 api,我在实体中创建了多部分文件字段,因此在这个实体中我拥有用户所需的全部数据,但现在我无法使用对象映射器将该多部分数据转换为 json 字符串。也请给出它的答案

spring-boot-test testcase mockmvc multipartentity
1个回答
0
投票

当我们在Spring Boot的Api端使用@ModelAttribute时 然后使用mockmvc从测试用例传递模拟数据 你需要传递 .param("var name","data")
像这样 mockMvc.perform(MockMvcRequestBuilders.multipart("/ekyc") .file(图像文件) .param("名字", "约翰") .param("middleName", "Doe") .param("姓氏", "史密斯") .param("电子邮件", "[电子邮件受保护]") .param("州", "加利福尼亚州") .param("城市", "洛杉矶") .param("num", "1234567890") .param("add", "主街 123 号") .param("add2", "公寓 123") .param("密码", "90001") .param("图像", "Xyz.jpg")) .andExpect(MockMvcResultMatchers.status().isOk());

© www.soinside.com 2019 - 2024. All rights reserved.