How to unittest a class using RestTemplate offline?

java, junit, resttemplate, spring, unit-testing

Solution

I suggest refactoring your client code to remove the direct dependency on `RestTemplate`, and replace it with references to `RestOperations`, which is the interface implemented by `RestTemplate`. and the one you should be coding to.

You can then inject a stub or mock of `RestOperations` into your code for unit testing, and inject a `RestTemplate` when using it for real.

Problem

I have a class which has direct dependency on the RestTemplate. I wish I have a JUnit test of it, offline. How could I mock a RestTemplate in my unittest?

Original source

Related problems