springboot token后端单元测试
时间: 2024-05-25 09:08:17 浏览: 23
Spring Boot Token 后端单元测试可以分为以下步骤:
1. 导入相关依赖:可以使用 JUnit 和 Mockito 这两个常用的测试框架,也需要导入 Spring Test 和 Spring Security Test 相关依赖。
2. 配置测试环境:可以使用 @RunWith(SpringRunner.class) 注解指定测试运行器,@SpringBootTest 注解指定测试启动类,@TestPropertySource 注解指定测试配置文件。
3. 编写测试用例:编写测试用例需要使用 @Test 注解标注方法,使用 Mockito 模拟依赖对象,使用 MockMvc 模拟 HTTP 请求。
4. 运行测试用例:可以使用 IDE 中的测试运行工具或者在命令行中使用 Maven 命令运行测试。
相关问题
springboot token后端单元测试测试类
Spring Boot Token后端单元测试可以通过MockMvc进行模拟测试,具体步骤如下:
1. 在测试类上添加注解:@RunWith(SpringRunner.class)和@SpringBootTest
2. 注入MockMvc:@Autowired private MockMvc mvc;
3. 编写测试方法,使用MockMvc发送请求并验证返回结果,例如:
```
@Test
public void testGetToken() throws Exception {
MvcResult result = mvc.perform(MockMvcRequestBuilders.get("/token")
.contentType(MediaType.APPLICATION_JSON))
.andExpect(MockMvcResultMatchers.status().isOk())
.andExpect(MockMvcResultMatchers.content().contentType(MediaType.APPLICATION_JSON))
.andReturn();
String response = result.getResponse().getContentAsString();
JSONObject jsonObject = new JSONObject(response);
String token = jsonObject.getString("token");
Assert.assertNotNull(token);
}
```
其中,MockMvcRequestBuilders用于构造请求,MockMvcResultMatchers用于验证返回结果。
SpringBoot+vue做请求头中加token,,从后端到前端,到所有的工具类已经请求拦截器和响应拦截器的配置请给写个详细完整的例子
好的,这里给出一个SpringBoot+Vue前后端分离的项目中实现请求头中加Token的完整示例。
1. 后端配置
首先,在后端的Spring Boot项目中,我们需要进行如下配置:
1.1 创建一个Token的工具类,用于生成、解析、校验Token。
```java
package com.example.demo.util;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
@Component
public class TokenUtils {
/**
* token有效期(小时)
*/
@Value("${token.expire.hours}")
private int expireHours;
/**
* token加密密钥
*/
@Value("${token.secret}")
private String secret;
/**
* 生成Token
*/
public String generateToken(String username) {
Map<String, Object> claims = new HashMap<>();
claims.put("username", username);
Date now = new Date();
Date expireTime = new Date(now.getTime() + expireHours * 60 * 60 * 1000);
return Jwts.builder()
.setClaims(claims)
.setIssuedAt(now)
.setExpiration(expireTime)
.signWith(SignatureAlgorithm.HS256, secret)
.compact();
}
/**
* 解析Token
*/
public Claims parseToken(String token) {
return Jwts.parser()
.setSigningKey(secret)
.parseClaimsJws(token)
.getBody();
}
/**
* 校验Token是否过期
*/
public boolean isTokenExpired(Date expirationTime) {
return expirationTime.before(new Date());
}
}
```
1.2 创建一个自定义的拦截器,在请求头中验证Token。
```java
package com.example.demo.interceptor;
import com.example.demo.util.TokenUtils;
import io.jsonwebtoken.Claims;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@Component
public class TokenInterceptor implements HandlerInterceptor {
@Autowired
private TokenUtils tokenUtils;
/**
* 在请求处理之前进行拦截,验证Token
*/
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
String token = request.getHeader("Authorization");
if (token == null || token.isEmpty()) {
response.setStatus(401);
return false;
}
Claims claims = tokenUtils.parseToken(token);
if (claims == null || tokenUtils.isTokenExpired(claims.getExpiration())) {
response.setStatus(401);
return false;
}
return true;
}
/**
* 在请求处理之后进行拦截
*/
@Override
public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
// do nothing
}
/**
* 在请求处理完成之后进行拦截
*/
@Override
public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
// do nothing
}
}
```
1.3 配置拦截器
在Spring Boot的配置文件中,将拦截器加入到拦截器链中。
```yaml
spring:
mvc:
# 配置拦截器
interceptor:
# 自定义拦截器
- class: com.example.demo.interceptor.TokenInterceptor
```
2. 前端配置
在前端的Vue项目中,我们需要进行如下配置:
2.1 创建一个请求拦截器,在请求头中添加Token。
```javascript
import axios from 'axios'
const instance = axios.create({
baseURL: process.env.VUE_APP_API_URL,
timeout: 10000
})
// 请求拦截器
instance.interceptors.request.use(
config => {
const token = localStorage.getItem('token')
if (token) {
config.headers.Authorization = token
}
return config
},
error => {
return Promise.reject(error)
}
)
export default instance
```
2.2 创建一个响应拦截器,在Token失效时跳转到登录页。
```javascript
import router from '@/router'
// 响应拦截器
instance.interceptors.response.use(
response => {
return response
},
error => {
if (error.response && error.response.status === 401) {
localStorage.removeItem('token')
router.push('/login')
}
return Promise.reject(error)
}
)
```
3. 测试
至此,我们已经完成了Token的生成、解析、校验,以及在请求头中添加Token,Token失效时跳转到登录页的配置。下面我们可以进行测试了。
3.1 登录时生成Token
在登录接口中,当用户名和密码正确时,生成Token并返回给前端。
```java
@RestController
@RequestMapping("/api/auth")
public class AuthController {
@Autowired
private TokenUtils tokenUtils;
@PostMapping("/login")
public ResponseEntity<?> login(@RequestBody AuthRequest request) {
// 验证用户名和密码
// ...
// 生成Token
String token = tokenUtils.generateToken(request.getUsername());
// 返回Token
return ResponseEntity.ok(new AuthResponse(token));
}
}
```
3.2 在请求头中添加Token
在每次请求时,将Token存储到localStorage中,在请求拦截器中获取Token并添加到请求头中。
```javascript
import api from '@/api'
export default {
login(username, password) {
return api.post('/auth/login', { username, password })
.then(res => {
const token = res.data.token
localStorage.setItem('token', token)
return token
})
}
}
```
3.3 Token失效时跳转到登录页
当后端返回401(未授权)时,响应拦截器会将Token从localStorage中删除,并跳转到登录页。
```javascript
import api from '@/api'
export default {
getProfile() {
return api.get('/user/profile')
.then(res => {
return res.data
})
}
}
```
以上就是完整的示例,希望可以帮助到你。
相关推荐
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![](https://img-home.csdnimg.cn/images/20210720083646.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)