下面针对该Controller编写测试用例验证正确性,具体如下。当然也可以通过浏览器插件等进行请求提交验证。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
|
@RunWith (SpringJUnit4ClassRunner. class )
@SpringApplicationConfiguration (classes = MockServletContext. class )
@WebAppConfiguration public class ApplicationTests {
private MockMvc mvc;
@Before
public void setUp() throws Exception {
mvc = MockMvcBuilders.standaloneSetup( new UserController()).build();
}
@Test
public void testUserController() throws Exception {
// 测试UserController
RequestBuilder request = null ;
// 1、get查一下user列表,应该为空
request = get( "/users/" );
mvc.perform(request)
.andExpect(status().isOk())
.andExpect(content().string(equalTo( "[]" )));
// 2、post提交一个user
request = post( "/users/" )
.param( "id" , "1" )
.param( "name" , "测试大师" )
.param( "age" , "20" );
mvc.perform(request)
.andExpect(content().string(equalTo( "success" )));
// 3、get获取user列表,应该有刚才插入的数据
request = get( "/users/" );
mvc.perform(request)
.andExpect(status().isOk())
.andExpect(content().string(equalTo( "[{\"id\":1,\"name\":\"测试大师\",\"age\":20}]" )));
// 4、put修改id为1的user
request = put( "/users/1" )
.param( "name" , "测试终极大师" )
.param( "age" , "30" );
mvc.perform(request)
.andExpect(content().string(equalTo( "success" )));
// 5、get一个id为1的user
request = get( "/users/1" );
mvc.perform(request)
.andExpect(content().string(equalTo( "{\"id\":1,\"name\":\"测试终极大师\",\"age\":30}" )));
// 6、del删除id为1的user
request = delete( "/users/1" );
mvc.perform(request)
.andExpect(content().string(equalTo( "success" )));
// 7、get查一下user列表,应该为空
request = get( "/users/" );
mvc.perform(request)
.andExpect(status().isOk())
.andExpect(content().string(equalTo( "[]" )));
}
} |
至此,我们通过引入web模块(没有做其他的任何配置),就可以轻松利用Spring MVC的功能,以非常简洁的代码完成了对User对象的RESTful API的创建以及单元测试的编写。其中同时介绍了Spring MVC中最为常用的几个核心注解:@Controller
,@RestController
,RequestMapping
以及一些参数绑定的注解:@PathVariable
,@ModelAttribute
,@RequestParam
等。