【问题标题】:How mock a function in mockito?如何在 mockito 中模拟一个函数?
【发布时间】:2020-07-14 17:37:57
【问题描述】:

我有一个函数,我想模拟它来做其他操作: 我写了这个(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 函数。

为什么?问题出在哪里?

感谢提示

问候

【问题讨论】:

  • 你能发布堆栈跟踪吗?此外,尚不清楚您的测试对象是什么以及如何向该对象提供 elasticServiceMock 实例
  • 另外,请显示所有导入语句以确保您使用正确的注释。
  • 这部分: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));不工作,我有这个错误: java.lang.NullPointerException at it.anas.communication.ApplicationTest.lambda$measureChannelProcessor$0(ApplicationTest.java:61) at org.mockito.internal.stubbing.StubbedInvocationMatcher.answer(StubbedInvocation Process finished退出代码 -1
  • 如果您可以发布完整的堆栈跟踪而不是缩短的堆栈跟踪将会很有帮助。另外,如果您要发布整个代码而不仅仅是测试

标签: java mocking mockito junit5


【解决方案1】:

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

这样:

import org.mockito.junit.jupiter.MockitoExtension;

@ExtendWith(MockitoExtension.class)
public class ApplicationTest {

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-09-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-05-30
    • 1970-01-01
    相关资源
    最近更新 更多