如何使用放心编写从外部url获取图像api的测试用例

How to write test cases for get image api from external url using rest assured

我有一张图片 url,它将作为我在 api 中的查询参数。 在这里,我使用查询参数获取图像并用 InputStreamResource.

响应

谁能帮我用rest assure写出合适的测试用例。请找到下面的示例代码。

假设示例图像 URL:http://asdas.reutyure.asdas.com/AA/pet/images/cat/Test-E0173.svg

图像控制器

@GetMapping(path = "/image")
    public ResponseEntity<InputStreamResource> getImage(@RequestParam("url") String url) {

        String fileName = url.substring(url.lastIndexOf('/') + 1, url.length());
        byte[] byteContent = imageService.getImageData(url);
        InputStream resourceInputStream = new ByteArrayInputStream(byteContent);

        return ResponseEntity.ok().header("Content-disposition", "attachment; filename=" + fileName)
                .contentType(MediaType.parseMediaType("application/octet-stream")).contentLength(byteContent.length)
                .body(new InputStreamResource(resourceInputStream));

    }

图片服务

public byte[] getImageData(String url) {
        try {
            RestTemplate restTemplate = new RestTemplate();
            byte[] responseEntity = restTemplate.getForObject(url, String.class).getBytes(StandardCharsets.ISO_8859_1);
            if (responseEntity != null) {
                return responseEntity;
            }
        } catch (Exception e) {
        }
        return new byte[0];
    }

ImageResourceTest

@TestInstance(Lifecycle.PER_CLASS)
class ImageResourceTest extends BaseTest {

    private static final String IMAGE_URL_PARAMETER = "http://asdas.reutyure.asdas.com/AA/pet/images/cat/Test-E0173.svg";


    @Test
    void getImageDetails() throws Exception {
    
    // How to write proper test cases for this functionality

        given() //
                .header(authHeader()) //
                .queryParam(IMAGE_URL, IMAGE_URL_PARAMETER) //
                .when() //
                .get(contextPath + "/image") //
                .then() //
                .statusCode(200);
    }

}

为您的 getImageData() 方法中使用的 RestTemplate 配置一个 MockRestServiceServer,以便它在预期的 URL 被命中时响应测试图像。 (我会使用来自应用程序上下文的自动装配 RestTemplate,无论是默认的还是自定义的。)

看起来像这样:

MockRestServiceServer mockServer = MockRestServiceServer.createServer(restTemplate);
...
mockServer.expect(ExpectedCount.once(), 
          requestTo(new URI(IMAGE_URL)))
          .andExpect(method(HttpMethod.GET))
          .andRespond(withStatus(HttpStatus.OK)
          .contentType(MediaType.IMAGE_JPEG_VALUE)
          .body(IOUtils.resourceToByteArray("data/test.jpg", getClass().getClassLoader()))
        );