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
execute
method. For that, you can use mocked versions of the actual parameters, such as theHttpMethod
and theHttpEntity
. If the underlyingexchange
method requires certain behavior from these parameters, you may need to stub that in with mockito'swhen
...thenReturn
methods.Once these mocked parameters are setup so that you can call your
execute
methods, 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
verify
methods to check, for example, that someHttpEntity
method is actually invoked.Technically, you could also verify that the rest template's
exchange
method 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'sverfiy
to check thatexchange
is 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 presentexecute
method it seems a bit overkill though.