1.pom配置


        org.springframework.boot
        spring-boot-starter-test

2.所需对象及Controller

public class User {
    private String id;
    private String username;
    private Date birthday;  

    public User(String id, String username) {
        this.id = id;
        this.username = username;
    }

    //get/set
}

构造一个queryUserList服务

@RestController
@RequestMapping(value="/user")
public class UserController {

            @GetMapping
            public List queryUserList(){
                //使用反射打印出信息
                System.out.println(ReflectionToStringBuilder.toString(condition,ToStringStyle.MULTI_LINE_STYLE));
                List users = new ArrayList<>();
                users.add(new User("1","张三"));
                users.add(new User("2","李四"));
                users.add(new User("3","王五"));
                return users;
            }
    }

编写mockmvc测试用例

@RunWith(SpringRunner.class)
@SpringBootTest
public class UserControllerTest {

    //伪造mvc环境
    @Autowired
    private WebApplicationContext mac;

    private MockMvc mockMvc;

    @Before
    public void setup() {
        mockMvc = MockMvcBuilders.webAppContextSetup(mac).build();
    }

    @Test
    public void whenGenInfoSuccess() throws Exception{
        String result = mockMvc.perform(get("/user")
                .contentType(MediaType.APPLICATION_JSON_UTF8)) 
                .andExpect(status().isOk())
                .andReturn().getResponse().getContentAsString();
                System.out.println(result);
    }
}