You need to enable JavaScript to run this app. 如何为使用Kafka Streams的应用编写含外部服务调用的单元测试用例
优惠活动
大模型
产品
解决方案
定价
更多

如何为使用Kafka Streams的应用编写含外部服务调用的单元测试用例

解决方案

你遇到的连接拒绝异常是因为测试环境中使用了真实的RestTemplate发起外部请求,没有对外部调用做Mock拦截,按以下步骤修改即可完成测试:

步骤1:测试类中添加MockBean替换真实RestTemplate

在你的TopologyTest测试类中,添加@MockBean注解注入Mock的RestTemplate,替换Spring上下文中的真实实例:

@Autowired
private ConfigurableApplicationContext appContext;
// 新增以下代码
@MockBean
private RestTemplate restTemplate;

步骤2:在测试方法中配置Mock返回规则

在testAppFlow方法中,发送测试消息前先定义RestTemplate的调用匹配规则和预设返回值:

@Test
void testAppFlow() {
    Custom customObj = getCustomObj();
    Result expectedResult = getResult();

    // 新增Mock规则,拦截RestTemplate的post请求返回预设结果
    // 注意替换为你业务代码中实际的restCompleteUri值,也可以用anyString()做模糊匹配
    when(restTemplate.postForEntity(
            eq("http://localhost:8080/endPointName"),
            any(HttpEntity.class),
            eq(Result.class)
    )).thenReturn(new ResponseEntity<>(expectedResult, HttpStatus.OK));

    ConsumerRecordFactory<String, Custom> resultFactory =
            new ConsumerRecordFactory<>(inTopic,
                    StreamsSerdes.String().serializer(), StreamsSerdes.CustomSerde().serializer());

    topologyTestDriver.pipeInput(resultFactory.create(
            inTopic,
            "1001",
            customObj
    ));

    ProducerRecord<String, Result> record =
            topologyTestDriver.readOutput(
                    outputTopic,
                    StreamsSerdes.String().deserializer(),
                    StreamsSerdes.ResultSerde().deserializer()
            );

    assertAll(() -> assertEquals("abc123", record.value().getABC()));
}

步骤3:导入Mockito静态依赖(如果未导入)

在测试类顶部添加以下静态导入,避免编译报错:

import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.when;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;

可选方案:使用MockRestServiceServer

如果你不想Mock整个RestTemplate,也可以使用Spring自带的MockRestServiceServer模拟外部接口返回,配置方式如下:

// 测试类中注入RestTemplate
@Autowired
private RestTemplate restTemplate;
private MockRestServiceServer mockServer;

// 在@BeforeAll中初始化MockServer
@BeforeAll
void setUp() {
    mockServer = MockRestServiceServer.createServer(restTemplate);
    // 其他原有初始化逻辑
}

@Test
void testAppFlow() {
    Custom customObj = getCustomObj();
    Result expectedResult = getResult();
    // 配置接口返回规则
    mockServer.expect(ExpectedCount.once(), 
            requestTo("http://localhost:8080/endPointName"))
            .andExpect(method(HttpMethod.POST))
            .andRespond(withSuccess(new ObjectMapper().writeValueAsString(expectedResult), MediaType.APPLICATION_JSON));
    
    // 原有测试逻辑
}

修改完成后重新运行测试,拓扑处理消息时就会直接返回你预设的Result对象,不会再发起真实的外部请求。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.17 20:15:03