Ask Your Question

Revision history [back]

click to hide/show revision 1
initial version
  1. Add dependencies: Firstly, you need to add the dependencies for Spring Test and Spring Boot Test in your pom.xml file.

  2. Create a test class: Create a JUnit test class and annotate it with @RunWith(SpringRunner.class) and @SpringBootTest(classes = MyApplication.class). Replace the MyApplication class with the class which contains the main method.

  3. Define RestTemplate: In the test class, define a RestTemplate instance by using @Autowired annotation. Spring will inject the RestTemplate instance into the test class through dependency injection.

  4. Write test methods: Write test methods for each REST endpoint you want to test. Use the RestTemplate instance to send mock requests to the endpoint and assert the response.

  5. Use Mockito: Use Mockito to mock any dependencies that the RestTemplate may have such as the client request factory.

Example Test Class:

@RunWith(SpringRunner.class) @SpringBootTest(classes = MyApplication.class) public class MyControllerTest {

@Autowired
private RestTemplate restTemplate;

@MockBean
private ClientHttpRequestFactory clientHttpRequestFactory;

@Before
public void setup() {
    Mockito.when(clientHttpRequestFactory.createRequest(Mockito.any(), Mockito.any())).thenReturn(new MockClientHttpRequest());
}

@Test
public void testGetMethod() {
    ResponseEntity<String> responseEntity = restTemplate.getForEntity("https://example.com/my-api", String.class);
    assertEquals(HttpStatus.OK, responseEntity.getStatusCode());
    assertEquals("Hello World", responseEntity.getBody());
}

}