Use mockito and junit to test images

brand :

I have a method that gets as parameter a MultipartFile object. Inside the method I use ImageIO.read(some_value) and ImageIO.write(some_value). I want to test this method with a mock image (I don't want to have images stored under the resource folder).

I've tried this: MockMultipartFile file = new MockMultipartFile("file", "boat.jpg", "image/jpeg", "content image".getBytes()); but without success.

public void f(MultipartFile file) throws IOException {
    final BufferedImage read = ImageIO.read(new ByteArrayInputStream(file.getBytes()));
    try (ByteArrayOutputStream baos = new ByteArrayOutputStream()) {
        ImageIO.write(read, "jpg", baos);
    }
 }

When I run the test the read variable has null value. I think that problem come from "content image".getBytes().

Is there a posibility to use mock images instead of real ones ?

O.O.Balance :

"content image".getBytes() returns a byte[] representation of the String "content image". How is ImageIO supposed to construct a BufferedImage from that?

You have two options here.

  1. Pass a byte[] of real data to MockMultipartFile
    • Since you mentioned you don't want to use mock image resources, this does not seem like a good fit.
  2. Mock ImageIO's static methods using Powermock
    • The mocked method will return a real BufferedImage your method can use, without having to read an image from a file.
    • This gives you the added benefit of being able to mock the call to write() as well, if you wish.
    • Sample code:
PowerMockito.mockStatic(ImageIO.class);

when(ImageIO.read(any())).thenAnswer(invocation -> {
    Object argument = invocation.getArguments()[0];
    // here you can check what arguments you were passed

    BufferedImage result = new BufferedImage(600, 400, BufferedImage.TYPE_INT_RGB); // create a BufferedImage object
    // here you can fill in some data so the image isn't blank

    return result;
});

Now, when your method under test calls imageIO.read(), it will receive the BufferedImage you construct in the lambda, without actually reading any files.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=107419&siteId=1