Spring Boot REST api Junit testing

Sridhar Narayanasamy
3 min readApr 13, 2023

--

JUnit testing is an essential part of software development that ensures the reliability and stability of your code. When it comes to testing REST APIs built with Spring Boot, JUnit testing is particularly crucial. In this blog post, we will explore how to use JUnit to test a Spring Boot REST API with sample code.

Step 1: Set up the Test Environment
To begin with, we need to set up the test environment for our Spring Boot application. In our case, we will use the @SpringBootTest annotation, which loads the entire application context and provides a way to test our REST API endpoints.

@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
public class MyRestControllerTest {

}

Step 2: Create a Test Class
Next, we need to create a test class for our REST API. We can use the @AutoConfigureMockMvc annotation to auto-configure the MockMvc object, which allows us to simulate HTTP requests and responses.

@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
@AutoConfigureMockMvc
public class MyRestControllerTest {

@Autowired
private MockMvc mockMvc;

}

Step 3: Write Test Cases
Once we have set up the test environment and created the test class, we can start writing our test cases. In our case, we will test the GET and POST methods of a REST API endpoint that retrieves and adds data to a database

@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
@AutoConfigureMockMvc
@Transactional
public class MyRestControllerTest {

@Autowired
private MockMvc mockMvc;

@Autowired
private MyRepository myRepository;

@Test
public void testGetMyObject() throws Exception {
MyObject myObject = new MyObject();
myObject.setName("Test Name");
myObject = myRepository.save(myObject);

mockMvc.perform(get("/api/my-objects/" + myObject.getId()))
.andExpect(status().isOk())
.andExpect(jsonPath("$.name", is(myObject.getName())));
}

@Test
public void testAddMyObject() throws Exception {
MyObject myObject = new MyObject();
myObject.setName("Test Name");

ObjectMapper objectMapper = new ObjectMapper();
String myObjectJson = objectMapper.writeValueAsString(myObject);

mockMvc.perform(post("/api/my-objects")
.contentType(MediaType.APPLICATION_JSON)
.content(myObjectJson))
.andExpect(status().isCreated())
.andExpect(jsonPath("$.name", is(myObject.getName())));

List<MyObject> myObjectList = myRepository.findAll();
assertThat(myObjectList.size(), is(1));
assertThat(myObjectList.get(0).getName(), is(myObject.getName()));
}

}

For the GET method, we can use the MockMvc object to simulate an HTTP GET request and assert that the response is correct. We can use the @Test annotation to mark our test method and include assertions that verify the status code, response body, and headers.

For the POST method, we can use the MockMvc object to simulate an HTTP POST request and verify that the data is successfully added to the database. We can use the @Transactional annotation to ensure that the transaction is rolled back after the test has completed.

Step 4: Run the Test
Finally, we can run our JUnit test and verify that our Spring Boot REST API is working as expected. We can use tools like Gradle or Maven to run the test from the command line, or we can run the test directly from our IDE.

Conclusion:

JUnit testing is an essential aspect of software development, and it becomes even more crucial when testing REST APIs built with Spring Boot. By using the @SpringBootTest annotation to set up the test environment, the @AutoConfigureMockMvc annotation to configure the MockMvc object, and writing test cases to test the HTTP methods of the REST API, we can ensure that our application is reliable and stable.

In this blog, we have shown how to test a REST API with JUnit in a Spring Boot application. By following these steps and writing test cases for our REST API, we can be confident that our code is working correctly and that we are delivering a high-quality product to our users.

--

--