简体   繁体   中英

How mock a function in mockito?

i have a function and i want mock it for to do anothers operations: I write this (java 8) but i have error:

java.lang.NullPointerException

my code is this:

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()));


}

there are 3 function mock.

when is running:

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

i have Error java.lang.NullPointerException but i have mocked elasticServiceMock.insert function.

Why? where is the problem?

Thanks for tips

Regards

In order to use the @Mock Annotation you need to have your Test class annotated with @ExtendWith(MockitoExtension.class) .

Like that:

import org.mockito.junit.jupiter.MockitoExtension;

@ExtendWith(MockitoExtension.class)
public class ApplicationTest {

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM