You need to enable JavaScript to run this app. 如何在Spring Boot Test中使用环境变量 避免测试硬编码密钥
优惠活动
大模型
产品
解决方案
定价
更多

如何在Spring Boot Test中使用环境变量 避免测试硬编码密钥

解决方案

核心问题原因

  • 你自定义的TokenForTest类没有被Spring容器管理,@Value注解只有在Spring托管的Bean中才会生效,普通类调用无法读取配置文件内容
  • 静态方法不能直接引用注入的非静态成员变量

具体修正方案

方案1:将Token生成类改造为Spring托管测试组件(适合多测试用例复用场景)

  1. 首先确认src/test/resources/application.properties中已经配置了测试用密钥:
secret=你的测试环境密钥
  1. 改造TokenForTest类,取消静态方法,添加Spring组件注解:
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import java.util.Date;

@Component
public class TokenForTest {
    @Value("${secret}")
    private String secret;

    public String generateTokenForTest() {
        Date today = new Date();
        Date expireDate = new Date(today.getTime() + 86400000L);
        return "Bearer " + Jwts.builder()
                .setIssuer("BeatSound API")
                .setSubject("1")
                .setIssuedAt(today)
                .setExpiration(expireDate)
                .signWith(SignatureAlgorithm.HS256, secret)
                .compact();
    }
}
  1. 改造测试类,加载Spring上下文并注入组件使用:
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.web.servlet.MockMvc;
import org.junit.jupiter.api.Test;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*;

@SpringBootTest
@AutoConfigureMockMvc
public class UserControllerTest {
    @Autowired
    private MockMvc mockMvc;
    @Autowired
    private TokenForTest tokenForTest;

    @Test
    void shouldReturnAllUsers() throws Exception {
        String token = tokenForTest.generateTokenForTest();
        this.mockMvc.perform(get("/api/v1/user")
                        .header("Authorization", token))
                .andExpect(content().contentType(MediaType.APPLICATION_JSON))
                .andExpect(status().isOk())
                .andDo(print())
                .andExpect(jsonPath("$.[*].id").exists())
                .andExpect(jsonPath("$.[*].name").exists())
                .andExpect(jsonPath("$.[*].email").exists())
                .andExpect(jsonPath("$.[*].password").exists());
    }
}

方案2:直接在测试类注入密钥(适合单测试用例场景)

如果不需要复用Token生成逻辑,可以直接在测试类中注入密钥生成Token:

@SpringBootTest
@AutoConfigureMockMvc
@TestPropertySource(locations = "classpath:application.properties")
public class UserControllerTest {
    @Autowired
    private MockMvc mockMvc;
    @Value("${secret}")
    private String secret;

    @Test
    void shouldReturnAllUsers() throws Exception {
        Date today = new Date();
        Date expireDate = new Date(today.getTime() + 86400000L);
        String token = "Bearer " + Jwts.builder()
                .setIssuer("BeatSound API")
                .setSubject("1")
                .setIssuedAt(today)
                .setExpiration(expireDate)
                .signWith(SignatureAlgorithm.HS256, secret)
                .compact();

        this.mockMvc.perform(get("/api/v1/user")
                        .header("Authorization", token))
                // 后续校验逻辑保持不变
                ;
    }
}

注意事项

  • 确保测试配置文件存放路径为src/test/resources,文件名无拼写错误
  • 如果你使用的是@WebMvcTest切片测试,需要添加@Import(TokenForTest.class)注解将组件导入测试上下文,否则会出现Bean找不到的报错

内容的提问来源于stack exchange,提问作者Rhames Lima

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.11 05:03:02