вызов mock.method возвращает ноль после заглушки - PullRequest
0 голосов
/ 28 ноября 2018

Я пытаюсь протестировать с помощью Mockito

мой тестируемый класс

@ Открытый класс службы DynatraceAPIServiceImpl реализует DynatraceAPIService {

private String apiUrl = "someurl";

private String apiToken = "sometoken";


@Override
public CreateCustomMetricResponse createCustomMetric(CreateCustomMetricRequest request) throws MonitoringException {
    logger.info("Inside create custom metric");

    if (request ==  null) {
        logger.error("create metric request is null");
        throw new MonitoringException("Create metric request is null");
    }

    String metricId = DynatraceConstants.METRIC_ID;
    String displayName = request.getDisplayName();

    CreateCustomMetricResponse response = httpUtils.postCustomMetric(apiUrl + "/v1/timeseries/" + metricId, apiToken, request);

    if (response == null) {
        logger.error("Error in creating custom metric with name : " + displayName);
        throw new MonitoringException("Error in creating custom metric with name : " + displayName);
    }

    logger.info("Custom metric : " + displayName + " is created successfully.");

    return response;
}

}

и мой тестовый класс:

@ RunWith (MockitoJUnitRunner.class) открытый класс DynatraceAPIServiceImplTest {

@InjectMocks
DynatraceAPIServiceImpl dynatraceAPIServiceImpl;

@Mock
DynatraceHttpUtils httpUtilsMock;

@Mock
DynatraceMonitoringUtils monitoringUtilsMock;

@Test(expected = MonitoringException.class)
public void createCustomMetricGetsNonNullResponse() throws MonitoringException {

    CreateCustomMetricRequest mockRequest = CreateCustomMetricRequest.builder()
            .displayName(DISPLAY_NAME)
            .types(new String[] {"test-type"})
            .build();
    CreateCustomMetricResponse response = CreateCustomMetricResponse.builder()
            .displayName(DISPLAY_NAME)
            .types(new String[] {"test-type"})
            .timeseriesId(TIMESERIES_ID)
            .build();

    boolean val = true;
    when(monitoringUtilsMock.isValidMetricIdValue(anyString())).thenReturn(val);
    when(httpUtilsMock.postCustomMetric(API_URL + "/v1/timeseries/" + METRIC_ID, API_TOKEN, mockRequest)).thenReturn(response);

    CreateCustomMetricResponse actualRespnose = dynatraceAPIServiceImpl.createCustomMetric(mockRequest);

    //verify(httpUtilsMock, times(1)).postCustomMetric(anyString(), anyString(), any(CreateCustomMetricRequest.class));
    //assertEquals(actualRespnose.getDisplayName(), DISPLAY_NAME);
}

}

Здесь, когда я выполняю тесты, это всегдав конечном итоге значение ответа будет равно нулю в строке

CreateCustomMetricResponse response = httpUtils.postCustomMetric (apiUrl + "/ v1 / timeseries /" + metricId, apiToken, request);

Даже если яЯ использовал оператор when () для возврата ответа, который я создал, он возвращает ноль.

Действительно признателен, если кто-то может сообщить мне, что здесь не так.Спасибо.

1 Ответ

0 голосов
/ 28 ноября 2018

Обычно это происходит, когда параметры, используемые в вашем производственном коде, отличаются от тех, с которыми вы озвучили вызов, простой способ выяснить - написать такой тест

when(httpUtilsMock.postCustomMetric(any(), any(), any())).thenReturn(response);

CreateCustomMetricResponse actualRespnose = dynatraceAPIServiceImpl.createCustomMetric(mockRequest);

verify(httpUtilsMock).postCustomMetric(API_URL + "/v1/timeseries/" + METRIC_ID, API_TOKEN, mockRequest);

Если вы это сделаетевы получите более приятную ошибку, показывающую разницу между тем, что сделал ваш код, и тем, для чего вы его проверили

. В целом, лучший подход - это использовать «строгие заглушки», так что если ваш код делает что-то отличное от того, что вы делаетезаглушил, потому что вы получите хорошую ошибку, сообщающую, что, где и почему

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...