2

In my service impl , when I use RestTemplate, I am unable to unit test my class methods(that have dependency on custom error response handler) as MockBean for resttemplate can't be used to setErrorHandler etc.

So I have to inject the RestTemplate into the method- pass it as method parameter, in my serviceimpl class.

Could you please let me know if it's a good practise to replace a Autowired RestTemplate injected from application context, with a method parameter(which helps in unit test) resttemplate which allows me create a RestTemplate instance and set required data on this object.

Appreciate if someone who has experienced this can respond.Thanks

ApprenticeWST
  • 117
  • 1
  • 7
  • would be good if you share all your code to understand better your problem – Carlos Nov 13 '19 at 23:55
  • In my opinion it is a good practice to inject the optional fields using setter methods and mandatory fields using constructors. It will help in unit testing as well as porting your service in non-spring environment. – Ashok Prajapati Nov 14 '19 at 04:34
  • You can mock almost anything and RestTemplate is not an exception https://stackoverflow.com/a/42428738/3957754 – JRichardsz Nov 14 '19 at 14:51
  • thanks all. Will find a suitable solution from your advice – ApprenticeWST Nov 15 '19 at 03:55

0 Answers0