Spring Boot二维码示例JUnit测试遇Zxing异常及400错误求助
Spring Boot二维码生成器测试问题解决方案
一、服务测试:QRCodeReader().decode()抛出com.google.zxing.NotFoundException
针对解码失败问题,按以下步骤排查修复:
确认二维码字节流转图像的逻辑正确性
生成二维码后,必须将字节数组正确转为BufferedImage,否则解码时无法识别图像格式:byte[] qrBytes = qrCodeService.generateQrCode("测试文本"); BufferedImage image = ImageIO.read(new ByteArrayInputStream(qrBytes));再基于该图像生成
BinaryBitmap用于解码:LuminanceSource source = new BufferedImageLuminanceSource(image); BinaryBitmap bitmap = new BinaryBitmap(new HybridBinarizer(source));调整二维码生成参数
确保生成的二维码尺寸足够(建议最小200x200像素),内容长度在对应QR码版本的支持范围内。示例生成逻辑:public byte[] generateQrCode(String text) throws WriterException, IOException { QRCodeWriter writer = new QRCodeWriter(); // 指定300x300的尺寸,避免因尺寸过小导致解码失败 BitMatrix matrix = writer.encode(text, BarcodeFormat.QR_CODE, 300, 300); // 字节流转换逻辑... }添加解码提示参数
解码时传入DecodeHintType参数,提升解码兼容性:Map<DecodeHintType, Object> hints = new HashMap<>(); hints.put(DecodeHintType.CHARACTER_SET, "UTF-8"); hints.put(DecodeHintType.TRY_HARDER, Boolean.TRUE); // 强制尝试更复杂的解码逻辑 Result result = new QRCodeReader().decode(bitmap, hints);
二、控制器测试:返回400 Bad Request(提示“Required part 'text' is not present”)
该问题源于请求参数未正确传递,按以下方式修复:
匹配控制器参数类型传递测试参数
如果控制器用@RequestParam("text")接收普通表单参数,测试代码需对应传递:mockMvc.perform(post("/api/qr/generate") .param("text", "测试内容") .contentType(MediaType.APPLICATION_FORM_URLENCODED)) .andExpect(status().isCreated());如果控制器用
@RequestPart("text")接收Multipart类型参数,测试需用MockPart传递:mockMvc.perform(post("/api/qr/generate") .part(new MockPart("text", "测试内容".getBytes(StandardCharsets.UTF_8))) .contentType(MediaType.MULTIPART_FORM_DATA)) .andExpect(status().isCreated());核对参数名与请求头
确保测试中传递的参数名与控制器注解中的value完全一致,同时请求头Content-Type需与参数类型匹配(表单用APPLICATION_FORM_URLENCODED,Multipart用MULTIPART_FORM_DATA)。
内容的提问来源于stack exchange,提问作者Sercan Noyan Germiyanoğlu
相关产品推荐
相关产品推荐

