Spring Boot-2 (@GetMapping注解)

一、 @GetMapping注解 简单实现以及如何测试

1.首先创建一个类 标明注解@SpringBootApplication

并且在main函数中写SpringApplication.run(类名.class, args)

 

2.建立一个类写controller,标明注解@RestController

在类中写一个函数实现get请求

标明注解@GetMapping

写法:

@GetMapping("/api/users")  --------> 不加参数写法

如下图 

 

 

3.对应测试的写法

首先测试类上标明注解

@SpringBootTest

@AutoConfigureMockMvc

 

其次,类中标明

@Autowired

private MockMvc mockMvc

 

接着,测试的类方法上标明

@Test

方法中写要测试的内容 

 

 

 前两个@Test为对验证码200和返回内容的测试

   第三个@Test为上面两种写法的合并更方便,可以一次测完

 

    @Test
    void should_assert_status_responseBody() throws Exception {
        //发送的请求为get请求 URL为"/api/users"
        mockMvc.perform(get("/api/users"))
                .andExpect(status().is(200))              // 期待返回的状态码为200
                .andExpect(content().string("Obama"));    //期待返回的内容为Obama
    }

 

posted @ 2019-07-27 19:01  灭世的蜜糖  阅读(7282)  评论(0编辑  收藏  举报