gpt4 book ai didi

java - 如何在mockito中模拟一个函数?

转载 作者:行者123 更新时间:2023-12-01 17:38:55 36 4
gpt4 key购买 nike

我有一个函数,我想模拟它来执行其他操作:我写这个(java 8)但我有错误:

java.lang.NullPointerException

我的代码是这样的:

public class ApplicationTest {

@Mock
MqttService mqttServiceMock;
@Mock
ElasticService elasticServiceMock;
@Mock
RestTemplate restTemplateMock;

private String message_out;
private String response_condition;
private boolean condition;

@Test
public void measureChannelProcessor() throws IOException {
ElasticConfiguration elasticConfiguration = null;
String resp=new ObjectMapper().readTree(this.getClass().getResource("/respElasticInsert.json")).toString();

when(restTemplateMock.postForEntity(anyString(), any(HttpEntity.class), eq(String.class)))
.thenReturn(new ResponseEntity<>(resp,HttpStatus.OK));

when(elasticServiceMock.insert(anyString(),anyString())).thenAnswer(invocation -> {
String index = (String) invocation.getArguments()[0];
String message = (String) invocation.getArguments()[0];

String requestUri = new StringBuilder()
.append(elasticConfiguration.baseRequestBuilder(index))
.toString();
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON);
HttpEntity<String> requestEntity = new HttpEntity<>(message, headers);
restTemplateMock = elasticConfiguration.customRestTemplate();
return restTemplateMock.postForEntity(requestUri, requestEntity, String.class);
});

doReturn((MessageHandler) message -> {
String index = "measure";
ResponseEntity<String> res = null;
message_out= message.getPayload().toString();
boolean checkMeasure = JsonUtility.checkMeasure(message_out);
if (checkMeasure ){
res = elasticServiceMock.insert(index, message_out);
}
System.out.println(res);
}).when(mqttServiceMock).measureChannelProcessor();

JsonNode measureJsonTest = new ObjectMapper().readTree(this.getClass().getResource("/MeasureTest.json"));
mqttServiceMock.measureChannelProcessor().handleMessage(new GenericMessage<>(measureJsonTest.toString()));


}

有 3 个函数模拟。

运行时间:

**res = elasticServiceMock.insert(index, message_out);**

我有错误java.lang.NullPointerException,但我模拟了elasticServiceMock.insert函数。

为什么?问题出在哪里?

谢谢指点

问候

最佳答案

为了使用@Mock注释,您需要使用@ExtendWith(MockitoExtension.class)注释您的测试类。

像这样:

import org.mockito.junit.jupiter.MockitoExtension;

@ExtendWith(MockitoExtension.class)
public class ApplicationTest {

关于java - 如何在mockito中模拟一个函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60996837/

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