Issue
I have a image url which will be my query parameter in the api.
Here I am fetching the image by using query parameter and respond back with InputStreamResource
.
Can anybody help me to write the proper test cases by using rest assured. Please find the below sample code.
Assume Sample Image URL : http://asdas.reutyure.asdas.com/AA/pet/images/cat/Test-E0173.svg
Image Controller
@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));
}
Image Service
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);
}
}
Solution
Configure a MockRestServiceServer
for the RestTemplate
used in your getImageData()
method so that it responds with a test image when an expected URL is hit. (I'd use an autowired RestTemplate
from the application context, either default or customized.)
It'll look something like this:
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()))
);
Answered By - dekkard
Answer Checked By - Mary Flores (JavaFixing Volunteer)