Ask Your Question
0

How to execute unit test for Springboot 3's RestTemplate with dependency injection?

asked 2023-07-21 02:50:16 +0000

scrum gravatar image

edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted
2

answered 2023-07-21 03:10:01 +0000

djk gravatar image
  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());
}

}

edit flag offensive delete link more

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account. This space is reserved only for answers. If you would like to engage in a discussion, please instead post a comment under the question or an answer that you would like to discuss

Add Answer


Question Tools

Stats

Asked: 2023-07-21 02:50:16 +0000

Seen: 11 times

Last updated: Jul 21 '23