Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to unittest a class using RestTemplate offline?

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?

like image 838
Dennis C Avatar asked Jan 10 '11 01:01

Dennis C


2 Answers

Sping 3.0 introduced RestTemplate. Since version 3.2, the Spring MVC test framework has provided the class MockRestServiceServer for unit testing client REST code.

like image 127
Raedwald Avatar answered Nov 20 '22 16:11

Raedwald


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.

like image 31
skaffman Avatar answered Nov 20 '22 16:11

skaffman