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.
It depends on what you want.
One way to use mocks is to make it easier to invoke the
executemethod. For that, you can use mocked versions of the actual parameters, such as theHttpMethodand theHttpEntity. If the underlyingexchangemethod requires certain behavior from these parameters, you may need to stub that in with mockito'swhen...thenReturnmethods.Once these mocked parameters are setup so that you can call your
executemethods, you will want to check that its result is correct.For checking the returned value, you can use traditional JUnit assertions.
Furthermore, you may want to check that certain interactions with the mocked objects actually took place. For that you can use mockito's
verifymethods to check, for example, that someHttpEntitymethod is actually invoked.Technically, you could also verify that the rest template's
exchangemethod is called. For that you'd need to mock the RestTemplate and inject the mock in you class under test. Then you can use mockito'sverfiyto check thatexchangeis called in the proper way. This typically is the sensible thing to do, especially if there are more methods to test in your class-under-test. For the presentexecutemethod it seems a bit overkill though.