gpt4 book ai didi

java - Mockito 使用 thenThrow 为 KafkaTemplate.send 抛出异常

转载 作者:行者123 更新时间:2023-12-05 02:42:50 29 4
gpt4 key购买 nike

我正在测试以下功能。

public boolean produceNumberOfPeople(NumberOfPeopleInPlaceDTO numberOfPeopleInPlaceDTO) {
final ProducerRecord<Integer, Integer> record = new ProducerRecord<>(
KafkaConfig.NUMBER_OF_PEOPLE_BY_PLACE_TOPIC,
numberOfPeopleInPlaceDTO.getId(),
numberOfPeopleInPlaceDTO.getNumberOfPeople());
try {
kafkaTemplate.send(record).get(2, TimeUnit.SECONDS);
return true;
}
catch (ExecutionException | TimeoutException | InterruptedException e) {
return false;
}
}

这是测试代码。

@Test
public void produceNumberOfPeopleTest() throws InterruptedException, ExecutionException, TimeoutException {
NumberOfPeopleInPlaceDTO numberOfPeopleInPlaceDTO = NumberOfPeopleInPlaceDTO.builder()
.id(1)
.numberOfPeople(10)
.build();
Mockito.when(kafkaTemplate.send(Mockito.any(ProducerRecord.class)))
.thenReturn(listenableFuture);
Mockito.when(listenableFuture.get(2,TimeUnit.SECONDS))
.thenThrow(TimeoutException.class);
Assert.assertFalse(placeService.produceNumberOfPeople(numberOfPeopleInPlaceDTO));
}

我定义了以下变量。

@Autowired
private PlaceService placeService;
@MockBean
private PlaceRepository placeRepository;
@MockBean
private KafkaTemplate<Integer, Integer> kafkaTemplate;
@MockBean
private ListenableFuture listenableFuture;

问题是 kafkaTemplate.send(record).get(2,TimeUnit.SECONDS) 没有抛出异常。所以测试一直失败。

如有任何遗漏,请提出建议。

最佳答案

我会建议创建失败的 ListenableFuture 对象而不是 Mock

SettableListenableFuture<SendResult<String, Object>> future = new SettableListenableFuture<>();
future.setException(new RuntimeException())

然后在 mock 中返回这个

 Mockito.when(kafkaTemplate.send(Mockito.any(ProducerRecord.class))).thenReturn(listenableFuture);

所以当get方法被调用它抛出 ExecutionException

This method returns the value if it has been set via set(Object), throws an ExecutionException if an exception has been set via setException(Throwable), or throws a CancellationException if the future has been cancelled.

关于java - Mockito 使用 thenThrow 为 KafkaTemplate.send 抛出异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67267850/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com