How do I mock a REST template exchange?

mock resttemplate exchange returning null
how to mock resttemplate exchange method using mockito
spring boot mock resttemplate exchange example
mockito resttemplate exchange
mockito resttemplate exchange throw exception
mock resttemplate exchange parameterizedtypereference
how to mock resttemplate postforentity method using mockito
mockito resttemplate exchange null

I have a service in which I need to ask an outside server via rest for some information:

public class SomeService {

    public List<ObjectA> getListofObjectsA() {
        List<ObjectA> objectAList = new ArrayList<ObjectA>();
        ParameterizedTypeReference<List<ObjectA>> typeRef = new ParameterizedTypeReference<List<ObjectA>>() {};
        ResponseEntity<List<ObjectA>> responseEntity = restTemplate.exchange("/objects/get-objectA", HttpMethod.POST, new HttpEntity<>(ObjectAList), typeRef);
        return responseEntity.getBody();
    }
}

How can I write a JUnit test for getListofObjectsA()?

I have tried with the below:

@RunWith(MockitoJUnitRunner.class)
public class SomeServiceTest {
    private MockRestServiceServer mockServer;

    @Mock
    private RestTemplate restTemplate;

    @Inject
   private SomeService underTest;

@Before
public void setup() {
    mockServer = MockRestServiceServer.createServer(restTemplate);
    underTest = new SomeService(restTemplate);
    mockServer.expect(requestTo("/objects/get-objectA")).andExpect(method(HttpMethod.POST))
            .andRespond(withSuccess("{json list response}", MediaType.APPLICATION_JSON));
}

    @Test
    public void testGetObjectAList() {
    List<ObjectA> res = underTest.getListofObjectsA();
    Assert.assertEquals(myobjectA, res.get(0));
}

However the above code does not work, it shows that responseEntitty is null. How can I correct my test to properly mock restTemplate.exchange?

You don't need MockRestServiceServer object. The annotation is @InjectMocks not @Inject. Below is an example code that should work

@RunWith(MockitoJUnitRunner.class)
public class SomeServiceTest {
    @Mock
    private RestTemplate restTemplate;

    @InjectMocks
    private SomeService underTest;

    @Test
    public void testGetObjectAList() {
        ObjectA myobjectA = new ObjectA();
        //define the entity you want the exchange to return
        ResponseEntity<List<ObjectA>> myEntity = new ResponseEntity<List<ObjectA>>(HttpStatus.ACCEPTED);
        Mockito.when(restTemplate.exchange(
            Matchers.eq("/objects/get-objectA"),
            Matchers.eq(HttpMethod.POST),
            Matchers.<HttpEntity<List<ObjectA>>>any(),
            Matchers.<ParameterizedTypeReference<List<ObjectA>>>any())
        ).thenReturn(myEntity);

        List<ObjectA> res = underTest.getListofObjectsA();
        Assert.assertEquals(myobjectA, res.get(0));
    }

How do I mock a REST template exchange?, You don't need MockRestServiceServer object. The annotation is @InjectMocks not @Inject . Below is an example code that should work The Spring Test module includes a mock server named MockRestServiceServer. With this approach, we configure the server to return a particular object when a specific request is dispatched through our RestTemplate instance. Finally, we can verify() on that server instance whether all expectations have been met or not.

ResponseEntity<String> responseEntity = new ResponseEntity<String>("sampleBodyString", HttpStatus.ACCEPTED);
when(restTemplate.exchange(
                           Matchers.anyString(), 
                           Matchers.any(HttpMethod.class),
                           Matchers.<HttpEntity<?>> any(), 
                           Matchers.<Class<String>> any()
                          )
                         ).thenReturn(responseEntity);

Integration Testing with Spring – Testing A REST API, Integration testing with Sprint for REST API testing. How we need to setup an integation test to inject mocks that we want to control behind the API. new HttpHeaders(); restTemplate = new TestRestTemplate(); entity = new restTemplate.exchange( createURLWithPort("/rest/student/name"), HttpMethod. A RestTemplateBuilder would be injected into the service, and the rest template constructed from it. In your test case, you can inject a Mocked RestTemplateBuilder which can, in turn, return a mocked RestTemplate. So, if you have the ability to refactor the original service, you can have some code that is much more testable.--More Details--

This is an example with the non depreated ArgumentMatchers class

when(restTemplate.exchange(
                ArgumentMatchers.anyString(),
                ArgumentMatchers.any(HttpMethod.class),
                ArgumentMatchers.any(),
                ArgumentMatchers.<Class<String>>any()))
             .thenReturn(responseEntity);

How do i mock RestTemplate exchange - spring - html, Trying the mocking as below : Mockito.doReturn(responseEntity).when(​restTemplate.exchange(anyString(), anyObject(), anyObject(), anyObject())); this gave me  Spring rest template is powerful library in built with spring rest module. Rest template exposes various methods to make a rest call to external service. Writing code and using rest template in your code is quite simple. But when it comes to write test case around rest template then you might need to write your source code carefully.

For me, I had to use Matchers.any(URI.class)

Mockito.when(restTemplate.exchange(Matchers.any(URI.class), Matchers.any(HttpMethod.class), Matchers.<HttpEntity<?>> any(), Matchers.<Class<Object>> any())).thenReturn(myEntity);

How to Mock Spring RestTemplate using PowerMockito, Mock spring RestTemplate to call rest web service using powermockito. public <T>ResponseEntity<T> exchange( String url, HttpMethod  Spring RestTemplate – exchange() method with GET and POST Requests The exchange() method Execute the HTTP method to the given URI template, writing the given HttpEntity to the request, and returns the response as ResponseEntity .

This work on my side.

ResourceBean resourceBean = initResourceBean();
ResponseEntity<ResourceBean> responseEntity  
    = new ResponseEntity<ResourceBean>(resourceBean, HttpStatus.ACCEPTED);
when(restTemplate.exchange(
    Matchers.anyObject(), 
    Matchers.any(HttpMethod.class),
    Matchers.<HttpEntity> any(), 
    Matchers.<Class<ResourceBean>> any())
 ).thenReturn(responseEntity);

modules/HttpClientEventListenerTest.java at master · motech , private RestTemplate restTemplate = Mockito.mock(RestTemplate.class);. @Test. public void restTemplate).exchange(anyString(), any(HttpMethod.class),. Spring RestTemplate methods are defined using generics. Below is the method definition which is used to call rest service. You can set expectation without specifying the request class of the HttpEntity.

spring-cloud-config/ConfigServicePropertySourceLocatorTests.java , In this spring boot junit example, learn to write Junit tests with RestTemplate to responses to travel over network and mock servlet container is not involved. Now that your RestTemplate has become a class member you can now properly mock through one of two ways. One, inject it using the @InjectMock, or use a setter method that you call from your test. Since you are using InjectMock in your code we can go with that.

Java Code Examples of org.springframework.web.client.RestTemplate, How can I correct my test to properly mock restTemplate.exchange ? Solution. You don't need MockRestServiceServer object. The annotation is @InjectMocks not  In this tutorial, we're going to illustrate the broad range of operations where the Spring REST Client – RestTemplate – can be used, and used well. For the API side of all examples, we'll be running the RESTful service from here. How to do Basic Authentication with the Spring RestTemplate. How to set up Digest Authentication for the Spring

Spring boot JUnit example with RestTemplate, java - test - resttemplate mock returning null . How do I mock a REST template exchange? (6) For me, I had to use Matchers.any(URI.class) Mockito. when

Comments
  • anyone has an idea?
  • How do we add contents to the myEntity.getBody()? Mine comes back null
  • Matchers are deprecated, you should use Mockito
  • @Angelina since it's a real object just use an appropriate constructor i.e ResponseEntity(T body, HttpStatus status)
  • @Mindaugas I´ve used the constructor but my response still is null ResponseEntity<String> response = new ResponseEntity<>( "a string",HttpStatus.OK );
  • @Marino make sure that your mocked method that is supposed to return the response entity is being called and that it is infact configured to return said entity
  • Doesn't work with org.hamcrest.Matchers and org.mockito.Matchers is deprecated in favor of hamcrest.
  • "Matchers" is deprecated and should be replaced with "ArgumentMatchers" because of a name clash. Class Matchers
  • You can use it with generic matcher too. ArgumentMatchers.<Class<?>>any())