You need to enable JavaScript to run this app. 如何为Spring Boot项目中的Sleuth编写单元测试?
优惠活动
大模型
产品
解决方案
定价
更多

如何为Spring Boot项目中的Sleuth编写单元测试?

Spring Boot Sleuth traceId 生成逻辑单元测试实现方案

前置依赖说明

确保测试环境已引入Sleuth核心依赖和Spring Boot测试依赖,Maven配置示例如下:

<!-- Sleuth 核心依赖 -->
<dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-starter-sleuth</artifactId>
</dependency>
<!-- Spring Boot 测试依赖 -->
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-test</artifactId>
    <scope>test</scope>
</dependency>

注意保持Spring Boot和Spring Cloud版本的兼容性,测试时默认开启Sleuth配置(spring.sleuth.enabled=true为默认值,无需额外配置)


场景1:验证HTTP接口请求自动生成traceId

Sleuth默认会将生成的traceId放入响应头X-B3-TraceId中,可通过MockMvc直接验证响应头是否符合预期:

import org.junit.jupiter.api.Test;
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 static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.header;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
import static org.hamcrest.Matchers.matchesRegex;

@SpringBootTest
@AutoConfigureMockMvc
public class SleuthTraceIdTest {

    @Autowired
    private MockMvc mockMvc;

    @Test
    void testHttpRequestGenerateTraceId() throws Exception {
        mockMvc.perform(get("/your/business/interface"))
                .andExpect(status().isOk())
                // 验证响应头存在traceId
                .andExpect(header().exists("X-B3-TraceId"))
                // 验证traceId格式符合规则:默认16位十六进制,开启128位traceId时为32位
                .andExpect(header().string("X-B3-TraceId", matchesRegex("[a-f0-9]{16}|[a-f0-9]{32}")));
    }
}

场景2:验证业务代码中traceId一致性

如果需要确认业务逻辑中获取的traceId和链路生成的traceId一致,可以先写一个测试接口返回当前链路的traceId,再对比响应头和返回值:

测试用Controller代码

import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import brave.Tracer;

@RestController
public class TestTraceController {
    private final Tracer tracer;

    public TestTraceController(Tracer tracer) {
        this.tracer = tracer;
    }

    @GetMapping("/test/get-trace-id")
    public String getCurrentTraceId() {
        return tracer.currentSpan().context().traceIdString();
    }
}

测试方法

import org.springframework.test.web.servlet.MvcResult;
import static org.junit.jupiter.api.Assertions.assertEquals;

@Test
void testTraceIdConsistency() throws Exception {
    MvcResult result = mockMvc.perform(get("/test/get-trace-id"))
            .andExpect(status().isOk())
            .andExpect(header().exists("X-B3-TraceId"))
            .andReturn();
    
    String headerTraceId = result.getResponse().getHeader("X-B3-TraceId");
    String businessTraceId = result.getResponse().getContentAsString();
    // 验证业务代码拿到的traceId和链路生成的traceId完全一致
    assertEquals(headerTraceId, businessTraceId);
}

场景3:验证异步场景traceId透传

针对异步方法、线程池调用的场景,可以通过测试验证traceId是否正常传递:

测试用异步Service代码

import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import brave.Tracer;

@Service
public class AsyncTestService {
    private final Tracer tracer;

    public AsyncTestService(Tracer tracer) {
        this.tracer = tracer;
    }

    @Async
    public String getAsyncTraceId() {
        return tracer.currentSpan().context().traceIdString();
    }
}

测试方法

import org.springframework.beans.factory.annotation.Autowired;
import brave.Tracer;
import static org.junit.jupiter.api.Assertions.assertEquals;

@Autowired
private AsyncTestService asyncTestService;
@Autowired
private Tracer tracer;

@Test
void testAsyncTraceIdPassThrough() {
    // 手动创建主线程span模拟请求链路
    var currentSpan = tracer.nextSpan().start();
    try (var scope = tracer.withSpanInScope(currentSpan)) {
        String mainThreadTraceId = currentSpan.context().traceIdString();
        // 调用异步方法
        String asyncThreadTraceId = asyncTestService.getAsyncTraceId();
        // 验证异步线程拿到的traceId和主线程一致
        assertEquals(mainThreadTraceId, asyncThreadTraceId);
    } finally {
        currentSpan.end();
    }
}

注意事项

  • 如果开启了128位traceId配置(spring.sleuth.trace-id128=true),只需要把traceId的正则匹配规则调整为[a-f0-9]{32}即可
  • 如果自定义了traceId的传播规则、响应头key,测试时要同步调整验证逻辑和生产配置保持一致
  • 测试类不要添加关闭Sleuth功能的相关注解或配置,避免测试失效

内容的提问来源于stack exchange,提问作者Ankit Kumar

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.15 03:24:08