У меня возникла проблема с написанием теста JUnit для метода в моем примере Spring Boot, показанном ниже. Я не могу справиться с фиктивной реализацией в HashMap в тесте JUnit, поскольку он выдает исключение нулевого указателя в url = MAP.getOrDefault(productType, clientUrl);
Вот фрагмент кода показано ниже
private static Map MAP;
private static String clientURL = "CLIENT_URL";
private static String adminURL = "ADMIN_URL";
/**
* Initializes the task list URLs based on the configuration properties.
*/
@PostConstruct
public void init() {
Map tempMap1 = new HashMap();
tempMap1.put("client", clientURL);
tempMap1.put("admin", adminURL);
MAP = Collections.unmodifiableMap(tempMap1);
}
public CustomResponse getResponse(RequestDTO request, String productType) {
String url = "";
if ("client".equalsIgnoreCase(productType)) {
url = MAP.getOrDefault(productType, clientUrl);
}else {
url = MAP.getOrDefault(productType, adminURl);
}
return restTemplate.postForObject(url,
request,
CustomResponse.class);
}
Вот тест JUnit, показанный ниже
private static Map MAP;
@BeforeClass
public static void setupClass() {
MAP = new HashMap();
MAP.put("client", "client-url");
MAP.put("admin", "admin-url");
}
@Test
public void testGetResponseForClient() {
// Given
RequestDTO request = new RequestDTO (/* provide necessary parameters */);
String productType = "client";
String expectedUrl = "client-url";
CustomResponse expectedResponse = new CustomResponse(200, "Success", new Object());
// When
when(MAP.getOrDefault(productType, clientUrl)).thenReturn(expectedUrl); // ERROR_LINE
when(restTemplate.postForObject(eq(expectedUrl), any(RequestDTO.class), eq(CustomResponse.class)))
.thenReturn(expectedResponse);
// Then
CustomResponse response = service.getTaskList(request, productType);
assertEquals(expectedResponse.getCode(), response.getCode());
// Verify
verify(restTemplate, times(1)).postForObject(expectedUrl, request, CustomResponse .class);
}
Вот ошибка в этой строке ( When(MAP.getOrDefault(productType, clientUrl)).thenReturn(expectedUrl); )
org.mockito.exceptions.misusing.MissingMethodInvocationException:
when() requires an argument which has to be 'a method call on a mock'.
For example:
when(mock.getArticles()).thenReturn(articles);
Also, this error might show up because:
1. you stub either of: final/private/equals()/hashCode() methods.
Those methods *cannot* be stubbed/verified.
Mocking methods declared on non-public parent classes is not supported.
2. inside when() you don't call method on mock but on some other object.
Как устранить проблему?
Пересмотренная часть
when(MAP.getOrDefault(productType, clientUrl)).thenAnswer(invocation -> {
String key = invocation.getArgument(0);
return mockMap.getOrDefault(key, invocation.getArgument(1));
});
Эта часть выдает ошибку, показанную ниже
org.mockito.exceptions.misusing.MissingMethodInvocationException:
when() requires an argument which has to be 'a method call on a mock'.
For example:
when(mock.getArticles()).thenReturn(articles);
Also, this error might show up because:
1. you stub either of: final/private/equals()/hashCode() methods.
Those methods *cannot* be stubbed/verified.
Mocking methods declared on non-public parent classes is not supported.
2. inside when() you don't call method on mock but on some other object.
Подробнее здесь: https://stackoverflow.com/questions/782 ... rexception
Как имитировать HashMap в тесте JUnit в Spring Boot (выдает исключение nullpointerException) ⇐ JAVA
-
- Похожие темы
- Ответы
- Просмотры
- Последнее сообщение