java - 如何使用 Mockito 模拟 RestTemplate 的最终新实例
问题描述
Component
public class MyService {
private final ObjectMapper objectMapper = new ObjectMapper();
private final RestTemplate restTemplate = new RestTemplate();
public void myMethod(){
------- codes to test above it------
HttpEntity<String> httpEntity = new HttpEntity<>(objectMapper
.writeValueAsString(message), httpHeaders);
String response = restTemplate
.postForObject(getUrl(), httpEntity, String.class);
}
}
我已经尝试过@Spy,但它不起作用
@InjectMocks
private MyService myService;
@Spy
private RestTemplate restTemplate;
when(restTemplate.postForObject(
getUrl(),
httpEntity,
String.class
)).thenReturn(getResponse());
解决方案
如果你想窥探:
@Test
void test(){
MyService myService = Mockito.spy(MyService.class);
myService.myMethod();
}
这样就得到了 RestTemplate 的实例。
我个人更喜欢将 RestTemplate 作为依赖项接收,这使得它易于模拟。
例如:
private final RestTemplate restTemplate;
public MyService(RestTemplate restTemplate) {
this.restTemplate = restTemplate;
}
在你的测试中
//@RunWith(MockitoJUnitRunner.class) //junit4
@ExtendWith(MockitoExtension.class) //junit 5
public class MyServiceTest {
@Mock
private RestTemplate restTemplate;
@InjectMocks
private MyService myService;
@Test
void test(){
when(restTemplate.postForObject(
getUrl(),
httpEntity,
String.class
)).thenReturn(getResponse());
//do whatever you like
}
}
推荐阅读
- python - 基本配置后 Cronjob 无法运行
- r - 如何用正负条标记水平条形图?(ggbarplot)
- javascript - 为什么 event.pageX 在 Firefox 中不起作用?
- c++ - Rstudio,配置:错误:在libgdal中找不到GDALAllRegister
- swift - 如何在 customTableViewCell 中获取 UITextField 的字符串并将其保存到 coreData?
- excel - Excel:替换特殊字符而不嵌套替换函数或创建函数
- json - Jmeter Maven clean verify 给出“未捕获的异常 java.lang.NoClassDefFoundError:com/jayway/jsonpath/internal/JsonReader”
- c# - C# Finding Nearest Value in a Generic Array?
- neural-network - 我可以在 Keras 中使用带有卷积神经网络的矩形图像吗?
- java - 我被困在我找不到的地方