1

I am trying to write unit test case for a function which takes a parameter of type "org.springframework.http.codec.multipart.FilePart" as an input.

However I am not able to figure out how to create a mock object of the class implementing above interface.

Browsing through some documentation, I found about MockMultipartFile, however I am not able to figure out if the above object can be used to construct an instance of org.springframework.http.codec.multipart.FilePart type.

private boolean isValidFile(FilePart filePart){
  boolean valid = true;
  // Do Something
  return valid;
}

Can someone help me out please ?

Paras
  • 3,191
  • 6
  • 41
  • 77
  • You could simply use a mocking framework like [Mockito](https://en.wikipedia.org/wiki/Mockito) to create mock objects for your unit tests. – maloomeister Sep 16 '20 at 11:26

2 Answers2

2

The best way for mocking FilePart is:

import java.io.File;
import org.junit.jupiter.api.Assertions; 
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.springframework.http.codec.multipart.FilePart;

import static org.mockito.BDDMockito.given;
import static org.mockito.BDDMockito.mock;

class ImageCreateDtoConverterTest {

  private static final String ACCOUNT_ID = "accountId";
  private static final Integer STATUS_CODE = 1;

  private ImageCreateDtoConverter imageCreateDtoConverter;

  @BeforeEach
  void setUp() {
   this.imageCreateDtoConverter = new ImageCreateDtoConverter();
  }

  @Test
  void convert() throws Exception {

   FilePart filePart = mock(FilePart.class);
   given(filePart.filename()).willReturn("TestImage.png");

   File file = new File(filePart.filename());

   var expected = new ImageCreateDto(STATUS_CODE, ACCOUNT_ID, file);

   var actual = imageCreateDtoConverter.convert(ACCOUNT_ID, STATUS_CODE, 
       filePart);

   Assertions.assertEquals(expected, actual);
  }
}
David Buck
  • 3,752
  • 35
  • 31
  • 35
1

I was figured out implementing by my own interface Part.

private static class PartImpl implements Part {
    @Override
    public String name() {
        return "name";
    }

    @Override
    public HttpHeaders headers() {
        return HttpHeaders.EMPTY;
    }

    @Override
    public Flux<DataBuffer> content() {
        return DataBufferUtils.read(
                new ByteArrayResource("name".getBytes(StandardCharsets.UTF_8)), factory, 1024);
    }
}

After just mock with my implemented class and it worked as expected.

P.S. For factory just use Default one

static final DataBufferFactory factory = new DefaultDataBufferFactory();

For FilePart just implement the same way.

Vielen Danke
  • 177
  • 1
  • 6