Pre Exam Test Practice (SSC | Banking | IAS | GATE | State Level | CLAT | Railways | Insurance | Teaching Exams | NDA | Defence | IES |State Exam )

Organizational Research By

Surprising Reserch Topic

unit test of file upload using mockmvcbuilders with standalone context and sprin

unit test of file upload using mockmvcbuilders with standalone context and sprin  using -'java,spring,unit-testing,spring-mvc,multipartform-data'

I'm using Spring Boot 1.2.5-RELEASE. I have a controller that receive a MultipartFile and a String

public class MyRESTController {

  private AService aService;

  @RequestMapping(method = RequestMethod.POST, consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
  public void fileUpload(
      @RequestParam(value = "file", required = true) final MultipartFile file,
      @RequestParam(value = "something", required = true) final String something) {
   aService.doSomethingOnDBWith(file, value);

Now, the service works well. I tested it with PostMan and eveything goes as expected.
Unfortunately, I cannot write a standalone unit test for that code. The current unit test is:

@SpringApplicationConfiguration(classes = MyApplication.class)
public class ControllerTest{

    MockMvc mockMvc;

    AService aService;

    MyRESTController controller;

  @Before public void setUp(){
    this.mockMvc = MockMvcBuilders.standaloneSetup(controller).build();

  public void testFileUpload() throws Exception{
        final File file = getFileFromResource(fileName);
        //File is correctly loaded
        final MockMultipartFile multipartFile = new MockMultipartFile("aMultiPartFile.txt", new FileInputStream(file));

        doNothing().when(aService).doSomethingOnDBWith(any(MultipartFile.class), any(String.class));

                        .requestAttr("file", multipartFile.getBytes())
                        .requestAttr("something", ":(")

Test fails with

java.lang.IllegalArgumentException: Expected MultipartHttpServletRequest: is a MultipartResolver configured?

Now, in the MultipartAutoConfiguration class from Spring Boot I see that a MultipartResolver is auto configured. But, I guess that with the standaloneSetup of MockMvcBuilders I cannot access this.

I tried several configurations of the unit test that I don't report for brevity. Especially, I also tried rest-assured as shown here, but honestly this doesn't work because it seems that I cannot mock the AService instance.

Any solution?

asked Oct 11, 2015 by ukohale
0 votes

Related Hot Questions

Government Jobs Opening