unable to mock RestTemplate response

724 views Asked by At

I wanted to mock the RestTemplate's result, but with my code below, it always went to do the Http. Can someone please advise? I think I have parts that I did wrongly, please help.

UserServiceTest.java @RunWith(SpringJUnit4ClassRunner.class)

public class UserServiceTest(){
    @InjectMock
    @Autowired
    UserService userservice;
    
    @Mock
    RestTemplate restTemplate;
    
    @Value(${aa.bb.cc})
    private String getfromapplicationpropertiesVal;
    
    @Test
    public void test1(){
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);
        
        String jsonBody = null;
        HttpEntity<String> entity = new HttpEntity<>(jsonBody, headers);
        
        String textContent = "result from junit";
        
        ResponseEntity<String> response = new ResponseEntity<>(textContent, HttpStatus.OK);
        
        String url = "http://localhost:8080/test/test.txt";
        
        doReturn(response).when(restTemplate).exchange(
            eq(url),
            any(HttpMethod.class),
            any(HttpEntity.class),
            any(Class.class)
        );
        
        userservice.test();
    }
}

UserService.java

@Service
public class UserService{
    @Autowired
    HttpHelperService httpHelperService;
    
    public void test(){
        String url = "http://localhost:8080/test/test.txt";
        String response = httpHelperService.cal(url, HttpMethod.GET);
        System.out.println(response);
    }
}

HttpHelperService.java

@Service
public class HttpHelperService{

    @Autowired
    private RestTemplate restTemplate;

    public String cal(String url, HttpMethod httpMethod){
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);
        
        String jsonBody = null;
        HttpEntity<String> entity = new HttpEntity<>(jsonBody, headers);
        
        String response = restTemplate.exchange(url, httpMethod, entity, String.class); //This part kept calling http when run the @Test
    }
}

RestTemplateConfig

@Configuration
public class RestTemplateConfig{
    @Bean
    public RestTemplate restTemplate(){
        return new RestTemplate();
    }
}
1

There are 1 answers

0
Ashish Patil On

Recommendation in these type of scenario is to use MockRestServiceServer & not mocking restTemplate.

You might do something like this:

@Mock
RestTemplate restTemplate;

@Autowired
MockRestServiceServer mockServer;

@BeforeEach
public void init(){
mockServer = MockRestServiceServer.createServer(restTemplate); //initialization 
}

And then invoke mock for your service something like :

mockServer.expect(requestTo(url))
        .andExpect(method(HttpMethod.GET))
        .andRespond(withSuccess("successOperation"));

-Alternatively, you can just mock your test() method:

when(mockedHttpHelperService).cal(anyString(),HttpMethod.GET).thenReturn("success");