0

I am using RestTemplate in a Spring project.Due to some reason i have created a RestTemplate Object inside a method. Example :

public class Post {

    public Post(){
    }

    public T postRequest(Object request){
        // Creating a Header Part
        // Creating a Restemplate instance
        RestTemplate rest = new RestTemplate();
        ResponseEntity<T> response = rest.exchange(......)
    }
}

My Question : How can we write Junit Test case for postRequest method even with mock. Because i can not autowired RestTemplate in PostTest class. Any Idea can help. Thanks in Advance.

  • What do you want to test? That RestTemplate works? Or that it is called correctly? – cyberbrain Jul 03 '23 at 17:23
  • 1
    Also why is your class named `Post` but the constructors name is `Test` and that is empty?? Please try to fix your example so that it compiles at least – cyberbrain Jul 03 '23 at 17:28
  • @cyberbrain That is just an example , I want to know how can i mock RestTemplate Exchange method when restemplate is defined inside a method rather than autowire in a class. Thanks – Rajat Sharma Jul 04 '23 at 07:18
  • Don't do it that way. Inject a `RestTemplate`, or a factory for `RestTemplate`s. – tgdavies Jul 04 '23 at 09:43
  • Do you have the same employer as this person?https://stackoverflow.com/questions/76609702/i-am-unable-to-mock-the-resttemplate-class-in-junit-testing-spring-boot?noredirect=1#comment135072489_76609702 – tgdavies Jul 04 '23 at 09:44
  • This question and its answer contain many possible solutions to this problem: https://stackoverflow.com/questions/74027324/why-are-my-mocked-methods-not-called-when-executing-a-unit-test – knittl Jul 04 '23 at 13:03

0 Answers0