首页 > 解决方案 > 如何用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 测试吗?

标签: springspring-mvcspring-bootspring-test

解决方案


当您测试控制器时,您可能正在进行集成测试。我编写基于 Spring MVC 的测试用例,并使用 Spring boot,更强大@AutoConfigureMockMvc

参考: https ://docs.spring.io/spring/docs/5.0.5.RELEASE/spring-framework-reference/testing.html#spring-mvc-test-framework

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());

    }

推荐阅读