本文介绍了如何用spring boot test来测试这个方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想测试这样的方法
@PostMapping(value = "/test")
public String test(@Valid TestModel model) {
return model.getUsername();
}
TestModel 就是这个
and the TestModel is this
@Getter
@Setter
public class TestModel {
private MultipartFile[] image1;
private MultipartFile[] image2;
private MultipartFile[] image3;
private String username;
private String password;
}
我可以使用 httpclient 来测试这个,但我认为这不是一个好主意,那么还有其他的 Spring 测试方法吗?
I can use httpclient to test this but I don't think this is a good idea,so any other methods with spring test?
推荐答案
@RunWith(SpringRunner.class)
@SpringBootTest
public class DemoApplicationTests {
@Autowired
private WebApplicationContext wac;
private MockMvc mockMvc;
@Before
public void before() {
this.mockMvc = MockMvcBuilders.webAppContextSetup(this.wac).build(); //构造MockMvc
}
@Test
public void test() throws Exception {
this.mockMvc.perform(MockMvcRequestBuilders.multipart("/test")
.file(new MockMultipartFile("image1", "filename1.txt", "text/plain", "some xml".getBytes()))
.file(new MockMultipartFile("image1", "filename2.txt", "text/plain", "some xml".getBytes()))
.file(new MockMultipartFile("image2", "filename3.txt", "text/plain", "some xml".getBytes()))
.file(new MockMultipartFile("image2", "filename4.txt", "text/plain", "some xml".getBytes()))
.file(new MockMultipartFile("image2", "filename5.txt", "text/plain", "some xml".getBytes()))
.file(new MockMultipartFile("image1", "filename6.txt", "text/plain", "some xml".getBytes()))
.file(new MockMultipartFile("image3", "filename7.txt", "text/plain", "some xml".getBytes()))
.param("username", "123")
.param("password", "123")
).andExpect(MockMvcResultMatchers.status().is(200));
}
}
这篇关于如何用spring boot test来测试这个方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!