单元测试

优质
小牛编辑
140浏览
2023-12-01

我们从 Hello World 项目入手,增加单元测试功能。

我们新家了一个名为hello-world-test的 Gradle 项目。

环境

  • Gradle 3.4.1
  • Spring Boot 1.5.2.RELEASE
  • Thymeleaf 3.0.3.RELEASE
  • Thymeleaf Layout Dialect 2.2.0
  • Spring Security Test 4.2.2.RELEASE

build.gradle

1. 修改项目的名称

修改 build.gradle 文件,让我们的hello-world项目成为一个新的项目。

修改内容也比较简单,修改项目名称及版本即可。

  1. jar {
  2. baseName = 'hello-world-test'
  3. version = '1.0.0'
  4. }

2. 指定依赖

  1. // 依赖关系
  2. dependencies {
  3. ......
  4. // 该依赖对于编译测试是必须的,默认包含编译产品依赖和编译时依
  5. testCompile('org.springframework.security:spring-security-test:4.2.2.RELEASE')
  6. ......
  7. }

编写测试类

测试 /users

首先我们测试 /users接口,编写UserControllerTest.java :

  1. @RunWith(SpringRunner.class)
  2. @SpringBootTest
  3. @AutoConfigureMockMvc
  4. public class UserControllerTest {
  5. @Autowired
  6. private MockMvc mockMvc;
  7. @Test
  8. public void testList() throws Exception {
  9. mockMvc.perform(MockMvcRequestBuilders.get("/users"))
  10. .andExpect(status().isOk());
  11. }
  12. }

运行 JUnit,结果是测试没有通过。在控制台,我们能看到如下请求和相应的结果:

  1. MockHttpServletRequest:
  2. HTTP Method = GET
  3. Request URI = /users
  4. Parameters = {}
  5. Headers = {}
  6. Handler:
  7. Type = null
  8. Async:
  9. Async started = false
  10. Async result = null
  11. Resolved Exception:
  12. Type = null
  13. ModelAndView:
  14. View name = null
  15. View = null
  16. Model = null
  17. FlashMap:
  18. Attributes = null
  19. MockHttpServletResponse:
  20. Status = 302
  21. Error message = null
  22. Headers = {X-Content-Type-Options=[nosniff], X-XSS-Protection=[1; mode=block], Cache-Control=[no-cache, no-store, max-age=0, must-revalidate], Pragma=[no-cache], Expires=[0], X-Frame-Options=[DENY], Location=[http://localhost/login]}
  23. Content type = null
  24. Body =
  25. Forwarded URL = null
  26. Redirected URL = http://localhost/login
  27. Cookies = []

可以看到响应的状态码为 302,重定向到了 http://localhost/login URL。

我们再次修改测试接口,这一次我们使用 mock 用户名为“waylau”角色权限为“USER”的用户:

  1. @Test
  2. @WithMockUser(username="waylau", password="123456", roles={"USER"}) // mock 了一个用户
  3. public void testListWithUser() throws Exception {
  4. mockMvc.perform(MockMvcRequestBuilders.get("/users"))
  5. .andExpect(status().isOk());
  6. }

这次,我们的测试用例通过。如果我们把用的角色权限改为“ADMIN”,会怎幺样呢?

  1. MockHttpServletRequest:
  2. HTTP Method = GET
  3. Request URI = /users
  4. Parameters = {}
  5. Headers = {}
  6. Handler:
  7. Type = null
  8. Async:
  9. Async started = false
  10. Async result = null
  11. Resolved Exception:
  12. Type = null
  13. ModelAndView:
  14. View name = null
  15. View = null
  16. Model = null
  17. FlashMap:
  18. Attributes = null
  19. MockHttpServletResponse:
  20. Status = 403
  21. Error message = Access is denied
  22. Headers = {X-Content-Type-Options=[nosniff], X-XSS-Protection=[1; mode=block], Cache-Control=[no-cache, no-store, max-age=0, must-revalidate], Pragma=[no-cache], Expires=[0], X-Frame-Options=[DENY]}
  23. Content type = null
  24. Body =
  25. Forwarded URL = null
  26. Redirected URL = null
  27. Cookies = []

看到测试失败后,控制台打印的信息,状态码为 403,错误信息为 “Access is denied”。