Spring boot Mock MVC
package com.xx.store.service.controller;
import com.google.gson.Gson;
import com.nisco.common.core.entity.ApiResult;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.http.MediaType;
import org.springframework.mock.web.MockMultipartFile;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.request.MockMvcRequestBuilders;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import org.springframework.web.context.WebApplicationContext;
import java.io.File;
import java.io.FileInputStream;
import java.util.ArrayList;
import java.util.List;
import static org.hamcrest.Matchers.is;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
@SpringBootTest
@RunWith(SpringRunner.class)
public class FdAttachCommonLocalTest {
@Autowired
private WebApplicationContext webApplicationContext;
private MockMvc mvc;
@Before
public void setupMockMvc(){
mvc = MockMvcBuilders.webAppContextSetup(webApplicationContext).build();
}
@Test
public void upload()
throws Exception {
final String BASE_DIR = "E:\\things_bu\\2021.8\\0826_文件存储测试\\";
final String[] FILES = new String[] {"application.yml", "BaseDataSourceConfig.java", "jenkins.war", "JH4J&打分系统.zip",
"PgyVisitor_4.9.0.37673.exe", "sonar-l10n-zh-plugin-8.9.jar", "金恒JH4J开发平台软件使用手册.docx"};
List<String> fileIds = new ArrayList<>();
for (String filename : FILES) {
File file = new File(BASE_DIR + filename);
//文件之外的参数
MockMultipartFile firstFile = new MockMultipartFile("file", "BaseDataSourceConfig.java",
MediaType.TEXT_PLAIN_VALUE, new FileInputStream(file));
mvc.perform(MockMvcRequestBuilders.fileUpload("/common/file/uploadFile").file(firstFile)//文件
.param("relativeId", "1").param("relativeType", "demo"))//参数
.andDo((result) -> {
System.out.println(result);
ApiResult apiResult =
new Gson().fromJson(result.getResponse().getContentAsString(), ApiResult.class);
fileIds.add(apiResult.getData().toString());
}).andExpect(status().isOk()).andExpect(jsonPath("$.code", is(1000)));
break;
}
System.out.println(fileIds);
}
}