Java-SpringBoot Test测试

这里写自定义目录标题

@Before
    public void setUp() {
        // 独立安装测试.
        
        mockMvc = MockMvcBuilders.webAppContextSetup(context).build();
        // 集成Web环境测试(此种方式并不会集成真正的web环境,而是通过相应的Mock API进行模拟测试,无须启动服务器)
    }

访问路径地址:

getmapping: 
mockMvc.perform(MockMvcRequestBuilders.get("/404").accept(MediaType.APPLICATION_JSON)).andExpect(status().isOk());

访问带参数的路径地址:

postmapping:
mockMvc.perform(MockMvcRequestBuilders.post("/login").contentType(MediaType.APPLICATION_JSON_UTF8).content(JSONUtil.parse(userParam).toString()))
mockMvc.perform(...).andReturn().getResponse();  返回MockHttpServletResponse response.
String json = response.getContentAsString;将返回结果显示为字符串.
JSONUtil.toBean(json, AuthenticationParam.class); 结果转换为某个类输出.(或者是转为json格式?..)

MockMvc mockMvc;不可以作为参数传到另一个类的属性中.但是可以通过构造函数参数 传递.

出现的问题:

1.明明访问进了接口,为何收不到 复杂 参数?
	查看接口参数接收是否 少了@RequestBody

@RequestBody为关键

带有文件的 和 参数的 ( 遗憾的是 fileUpload 已为过期方法.还没找到替代方法)

//  .file(new MockMultipartFile("file", "test", "application/ms-excel", new FileInputStream(..)))
//  "file"为参数中的名称.
 ResultActions resultActions = mockMvc.perform(MockMvcRequestBuilders.fileUpload("/data/project/file").
                    file(new MockMultipartFile("file", "test", "application/ms-excel", new FileInputStream(new File(propertyPath))))
                    .param("enum","WITER" )
                    .param("int","0" )
                    .param("string",projectNamestring )
                    .param("long",0.0001 )
                    .param("list","0,1,2,3" )
                    .cookie(cookies));
.param很智能,可以自动转换value 的类型.



//两个文件 

MockMultipartFile firstFile = new MockMultipartFile("data", "filename.txt", "text/plain", "some xml".getBytes());  
        MockMultipartFile secondFile = new MockMultipartFile("data", "other-file-name.data", "text/plain", "some other type".getBytes());  
        MockMultipartFile jsonFile = new MockMultipartFile("json", "", "application/json", "{\"json\": \"someValue\"}".getBytes());  
 
 MockMvc mockMvc = MockMvcBuilders.webAppContextSetup(webApplicationContext).build();  
        mockMvc.perform(MockMvcRequestBuilders.fileUpload("/upload")  
                        .file(firstFile)  
                        .file(secondFile).file(jsonFile)  
                        .param("some-random", "4"))  
                    .andExpect(status().is(200))  
                    .andExpect(content().string("success"));  
                    [摘自 tobato ](https://www.iteye.com/blog/tobato-2315174)

你可能感兴趣的:(spring,boot,java)