首页 > 解决方案 > 如何使用 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());

标签: javaunit-testingjunitmockito

解决方案


如果你想窥探:

@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
   }

}

推荐阅读