当前位置:   article > 正文

Spring Boot项目集成PowerMock写单元测试_spring-boot-starter-test powermock

spring-boot-starter-test powermock

引用

1.Java单元测试技巧之PowerMock

集成依赖

  1. <dependencyManagement>
  2. <dependency>
  3. <groupId>org.powermock</groupId>
  4. <artifactId>powermock-module-junit4</artifactId>
  5. <version>${powermock.version}</version>
  6. <scope>test</scope>
  7. </dependency>
  8. <dependency>
  9. <groupId>org.powermock</groupId>
  10. <artifactId>powermock-api-mockito2</artifactId>
  11. <version>${powermock.version}</version>
  12. <scope>test</scope>
  13. </dependency>
  14. </dependencyManagement>
  15. <dependencies>
  16. <dependency>
  17. <groupId>org.springframework.boot</groupId>
  18. <artifactId>spring-boot-starter-test</artifactId>
  19. <scope>test</scope>
  20. </dependency>
  21. <dependency>
  22. <groupId>org.powermock</groupId>
  23. <artifactId>powermock-module-junit4</artifactId>
  24. <scope>test</scope>
  25. </dependency>
  26. <dependency>
  27. <groupId>org.powermock</groupId>
  28. <artifactId>powermock-api-mockito2</artifactId>
  29. <scope>test</scope>
  30. </dependency>
  31. </dependencies>

控制层代码

  1. @Slf4j
  2. @RestController
  3. public class LoginController {
  4. @Autowired
  5. private LoginService loginService;
  6. @PostMapping("/login")
  7. public BaseResponse<String> login(@RequestBody LoginUserEntity loginUser) {
  8. String token = loginService.loginSys(loginUser);
  9. log.info("用户 {} 登录成功", loginUser.getUsername());
  10. return BaseResponse.success(token);
  11. }
  12. @GetMapping("/test/page")
  13. public BaseResponse<String> testPage() {
  14. return BaseResponse.success("test page");
  15. }
  16. }

光标对准要测试的方法,快捷键command+shift+t会在test目录下创建对应的测试目录

测试代码

  1. RunWith(PowerMockRunner.class)
  2. public class LoginControllerTest {
  3. @Mock
  4. private LoginService loginService;
  5. @InjectMocks
  6. private LoginController loginController;
  7. @Test
  8. public void loginSuccessTest() {
  9. String token = "this is token";
  10. LoginUserEntity loginUserEntity = LoginUserEntity.builder()
  11. .username("admin")
  12. .password("admin")
  13. .build();
  14. Mockito.when(loginService.loginSys(loginUserEntity)).thenReturn(token);
  15. BaseResponse<String> baseResponse = loginController.login(loginUserEntity);
  16. Assert.assertEquals(200, baseResponse.getCode());
  17. Assert.assertEquals("success", baseResponse.getMsg());
  18. Assert.assertEquals(token, baseResponse.getData());
  19. }
  20. @Test
  21. public void testPage() {
  22. BaseResponse<String> baseResponse = loginController.testPage();
  23. Assert.assertEquals(200, baseResponse.getCode());
  24. Assert.assertEquals("success", baseResponse.getMsg());
  25. }
  26. }

service代码

  1. @Service
  2. @Slf4j
  3. public class LoginServiceImpl implements LoginService {
  4. @Autowired
  5. private AuthenticationManager authenticationManager;
  6. @Autowired
  7. private JwtTokenUtil jwtTokenUtil;
  8. @Override
  9. public String loginSys(LoginUserEntity loginUser) {
  10. final Authentication authentication = authenticate(loginUser.getUsername(), loginUser.getPassword());
  11. //存储认证信息
  12. SecurityContextHolder.getContext().setAuthentication(authentication);
  13. //生成token
  14. log.info("{} 登录,生成token", loginUser.getUsername());
  15. final SysUserDetails userDetail = (SysUserDetails) authentication.getPrincipal();
  16. final String token = jwtTokenUtil.generateAccessToken(userDetail);
  17. //存储token
  18. jwtTokenUtil.putToken(loginUser.getUsername(), token);
  19. return token;
  20. }
  21. private Authentication authenticate(String username, String password) {
  22. try {
  23. // 该方法会去调用userDetailsService.loadUserByUsername()去验证用户名和密码,
  24. // 如果正确,则存储该用户名密码到security 的 context中
  25. return authenticationManager.authenticate(new UsernamePasswordAuthenticationToken(username, password));
  26. } catch (DisabledException | BadCredentialsException e) {
  27. throw new PermissionDeniedException("用户名或密码错误,请重新登录");
  28. }
  29. }
  30. }

 测试代码

  1. @RunWith(PowerMockRunner.class)
  2. public class LoginServiceImplTest {
  3. @InjectMocks
  4. private LoginServiceImpl loginService;
  5. @Mock
  6. private AuthenticationManager authenticationManager;
  7. @Mock
  8. private JwtTokenUtil jwtTokenUtil;
  9. @Test
  10. public void loginSysSuccessTest() throws Exception {
  11. String token = "this is token";
  12. LoginUserEntity loginUserEntity = LoginUserEntity.builder()
  13. .username("admin")
  14. .password("admin")
  15. .build();
  16. SysUserDetails sysUserDetails = new SysUserDetails();
  17. sysUserDetails.setId(1);
  18. sysUserDetails.setUsername("admin");
  19. sysUserDetails.setPassword("admin");
  20. sysUserDetails.setRoles(null);
  21. Mockito.when(authenticationManager.authenticate(new UsernamePasswordAuthenticationToken(loginUserEntity.getUsername(), loginUserEntity.getPassword())))
  22. .thenReturn(new UsernamePasswordAuthenticationToken(sysUserDetails, "admin"));
  23. PowerMockito.when(loginService, "authenticate", loginUserEntity.getUsername(), loginUserEntity.getPassword())
  24. .thenReturn(new UsernamePasswordAuthenticationToken(sysUserDetails, "admin"));
  25. Mockito.when(jwtTokenUtil.generateAccessToken(sysUserDetails)).thenReturn(token);
  26. String actualToken = loginService.loginSys(loginUserEntity);
  27. Assert.assertEquals(token, actualToken);
  28. }
  29. @Test(expected = PermissionDeniedException.class)
  30. public void loginSysFailedTest() throws Exception {
  31. String token = "this is token";
  32. LoginUserEntity loginUserEntity = LoginUserEntity.builder()
  33. .username("admin")
  34. .password("admin")
  35. .build();
  36. SysUserDetails sysUserDetails = new SysUserDetails();
  37. sysUserDetails.setId(1);
  38. sysUserDetails.setUsername("admin");
  39. sysUserDetails.setPassword("admin");
  40. sysUserDetails.setRoles(null);
  41. Mockito.when(authenticationManager.authenticate(new UsernamePasswordAuthenticationToken(loginUserEntity.getUsername(), loginUserEntity.getPassword())))
  42. .thenThrow(new BadCredentialsException("bad credential"));
  43. loginService.loginSys(loginUserEntity);
  44. }
  45. }

 测试结果

 

 

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/知新_RL/article/detail/366846?site
推荐阅读
相关标签
  

闽ICP备14008679号