spring - 如何用spring boot test来测试这个方法?
问题描述
我想测试这样的方法
@PostMapping(value = "/test")
public String test(@Valid TestModel model) {
return model.getUsername();
}
TestModel 就是这个
@Getter
@Setter
public class TestModel {
private MultipartFile[] image1;
private MultipartFile[] image2;
private MultipartFile[] image3;
private String username;
private String password;
}
我可以使用 httpclient 来测试这个,但我认为这不是一个好主意,那么还有其他方法可以使用 spring 测试吗?
解决方案
当您测试控制器时,您可能正在进行集成测试。我编写基于 Spring MVC 的测试用例,并使用 Spring boot,更强大@AutoConfigureMockMvc
http://www.baeldung.com/spring-boot-testing
配置后是这样的:
@RunWith(SpringRunner.class)
@SpringBootTest(
webEnvironment = WebEnvironment.RANDOM_PORT,
classes = Application.class)
@AutoConfigureMockMvc
@TestPropertySource(
locations = "classpath:test.properties")
public class ControllerTest {
@Autowired
private MockMvc mvc;
@Test
public void test(){
mvc.perform(MockMvcRequestBuilders
.post("/test")
.contentType(MediaType.APPLICATION_JSON).content(content))
.andExpect(status().isOk())
.andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8))
.andDo(print());
}
推荐阅读
- api - 如何正确设置 Curl 选项以使用 Filemaker 16-18 将多部分文件上传到 Google Drive
- python - python递归oop与功能
- maven - 如何在控制台中打印集成测试(maven failsafe)?
- sql - 休眠中的查询错误:SQL 错误:156,SQLState:S0001
- powershell - Adobe flash player powershell远程安装问题
- python - upload_blob 函数中的 Azure python asyncio 内存耗尽
- c# - C# 根据位图位置裁剪位图
- php - Woocommerce 自定义简码返回零值
- spring-boot - 无法使用带有自定义对象的地图创建实体对象
- r - 使用 name_repair 以编程方式处理重复的列