How to write unit test case for Multipart file?
@Data
Class Document {
String name;
byte[] byteFile;
}
@Service
public class DocService {
public Document makeDocument(Multipart file, String name) {
Document document = makeDocument(file, name);
return document;
}
private Document document() {
Document document = new Document();
document.setName(name);
document.setByteFile(file.getbyte());
return document;
}
}
MockMultipartFile file =
new MockMultipartFile("file","test contract.pdf",MediaType.APPLICATION_PDF_VALUE,
"<<pdf data>>".getBytes(StandardCharsets.UTF_8));
@test
void testMakeDocument() {
when(docService.makeDocument(file, "any")).thenReturn(document);
assertNotNull();//
assertEquals();
}
Getting this error :
when() requires an argument which has to be ‘a method call on a mock’.
when(docService.makeDocument(file, "any")).thenReturn(document);
How to write test case for this ?
Tried various approach like using
@Mock
Multipart file
but then throws document cannot be returned by getbytes() getbyte() should be return byte[].
How to write unit test case ?
>Solution :
After a couple of fixes in your code ( the updated code is included ) an approach to test it is the following :
public class DocServiceTest {
@Test
public void testMakeDocument() {
Multipart mMultipart = mock(Multipart.class);
final byte[] bytes = {1, 2, 3, 4};
when(mMultipart.getbyte()).thenReturn(bytes);
final DocService docService = new DocService();
final Document aTest = docService.makeDocument(mMultipart, "aTest");
assertNotNull(aTest);
assertEquals("aTest", aTest.getName());
assertEquals(bytes, aTest.getByteFile());
}
}
As for your updated code :
@Service
public class DocService {
public Document makeDocument(Multipart file, String name) {
return document(file, name);
}
private Document document(Multipart file, String name) {
Document document = new Document();
document.setName(name);
document.setByteFile(file.getbyte());
return document;
}
}
@Data
public class Document {
String name;
byte[] byteFile;
}
This is included as it applies to any "Multipart" you are going to test. As you did not have an include to use the same an interface is placed to substitute it.
public interface Multipart {
byte[] getbyte();
}