Мой класс:
Код: Выделить всё
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
public class MyClass {
public String getString() {
// object need mocking
ObjectMapper mapper = new ObjectMapper()
try {
// method need mocking
return mapper.writeValueAsString(List.of("1", "2"));
}
catch (JsonProcessingException e) {
throw new RuntimeException(e);
}
}
}
Код: Выделить всё
@Test
public void test_get_string() throws Exception {
ObjectMapper mapper = Mockito.mock(ObjectMapper.class);
Mockito.when(mapper.writeValueAsString(Mockito.anyList()))
.thenThrow(JsonProcessingException.class);
Assertions.assertThrows(RuntimeException.class, () -> {
new MyClass().getString();
});
// -> failed
// Expected RuntimeException but nothing was thrown
}
Код: Выделить всё
public class MyClass {
// make mapper a property
private ObjectMapper mapper;
public MyClass(ObjectMapper mapper) {
this.mapper = mapper;
}
public String getString() {
try {
return mapper.writeValueAsString(List.of("1", "2"));
}
catch (JsonProcessingException e) {
throw new RuntimeException(e);
}
}
}
Код: Выделить всё
@Test
public void test_get_string() throws Exception {
ObjectMapper mapper = Mockito.mock(ObjectMapper.class);
Mockito.when(mapper.writeValueAsString(Mockito.anyList()))
.thenThrow(JsonProcessingException.class);
Assertions.assertThrows(RuntimeException.class, () -> {
// pass mapper on creating object
new MyClass(mapper).getString();
}); // -> success
}
Подробнее здесь: https://stackoverflow.com/questions/781 ... ethod-call
Мобильная версия