Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to write mockito junit for Resttemplate exchange method

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.

like image 665
Java Learing Avatar asked Jun 15 '15 06:06

Java Learing


People also ask

What is RestTemplate Exchange ()?

The exchange method executes the request of any HTTP method and returns ResponseEntity instance. The exchange method can be used for HTTP DELETE, GET, HEAD, OPTIONS, PATCH, POST, PUT, TRACE methods. Using exchange method we can perform CRUD operation i.e. create, read, update and delete data.


2 Answers

@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());
    }
 }
like image 97
Robin Schürer Avatar answered Sep 20 '22 09:09

Robin Schürer


I think the most convenient and appropriate approach in this case (which is client side REST testing using RestTemplate) will be MockRestServiceServer provided by Spring Testing framework.

like image 21
Marcin Kłopotek Avatar answered Sep 21 '22 09:09

Marcin Kłopotek