How to write mockito junit for Resttemplate exchange method

Java Learing picture Java Learing · Jun 15, 2015 · Viewed 35.5k times · Source

How to write mockito junit for the method below:

@Autowired
RestTemplate restTemplate;

ResponseEntity<?> execute(final String url, HttpMethod httpMethod,
                          HttpEntity<?> entityRequest,
                          String.class, 
                          Map<String, String> urlVariables){
    restTemplate.exchange(url, httpMethod, entityRequest, responseType, urlVariables);
}

Please help me how to write.

Answer

Robin Sch&#252;rer picture Robin Schürer · Jun 15, 2015
@RunWith(MockitoJUnitRunner.class)
public class ToTestTest {

  @InjectMocks
  private YourClass toTest;

  @Mock
  private RestTemplate template;

  @Test
  public void test() {
    toTest.execute(Mockito.anyString(), Mockito.any(), Mockito.any(), 
                   Mockito.any(), Mockito.any());

    Mockito.verify(template, Mockito.times(1))
                    .exchange(Mockito.anyString(),
                                    Mockito.<HttpMethod> any(),
                                    Mockito.<HttpEntity<?>> any(),
                                    Mockito.<Class<?>> any(),
                                    Mockito.<String, String> anyMap());
    }
 }