码迷,mamicode.com
首页 > 编程语言 > 详细

spring boot——MockMvc的用法

时间:2018-12-22 12:38:25      阅读:156      评论:0      收藏:0      [点我收藏+]

标签:add   反射   throws   tty   ppc   throw   dexp   web   type   

1.pom配置

<dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-test</artifactId>
</dependency>

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<User> queryUserList(){
                //使用反射打印出信息
                System.out.println(ReflectionToStringBuilder.toString(condition,ToStringStyle.MULTI_LINE_STYLE));
                List<User> 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);
    }
}

spring boot——MockMvc的用法

标签:add   反射   throws   tty   ppc   throw   dexp   web   type   

原文地址:http://blog.51cto.com/mazongfei/2334045

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!