➤ How to Code a Game
➤ Array Programs in Java
➤ Java Inline Thread Creation
➤ Java Custom Exception
➤ Hibernate vs JDBC
➤ Object Relational Mapping
➤ Check Oracle DB Size
➤ Check Oracle DB Version
➤ Generation of Computers
➤ XML Pros & Cons
➤ Git Analytics & Its Uses
➤ Top Skills for Cloud Professional
➤ How to Hire Best Candidates
➤ Scrum Master Roles & Work
➤ CyberSecurity in Python
➤ Protect from Cyber-Attack
➤ Solve App Development Challenges
➤ Top Chrome Extensions for Twitch Users
➤ Mistakes That Can Ruin Your Test Metric Program
Spring Boot Rest API Unit Testing (JUnit with Mockito) | The spring-boot-starter-test
dependency includes junit-jupiter
, vintage
, mockito
dependencies.
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
</dependency>
Mocking means creating dummy implementations or objects. If we want to test the Spring Boot application, then the following dummies are required:-
- Component Scanning
- Auto Configuration for Web Application
- Spring Container [AnnotationConfigServletWebApplicationContext]
- Request objects
- Environment details(props)
We need to provide all the above details using Mock support. If run starter class that takes care of all above thing. But this time we are running a Test class.
Also see:-
- Unit Testing in Java
- JUnit Annotations with Examples
- JUnit Assert Methods Example
- Mockito With Examples
Setup Full Environment (equal work to starter class)
- Loading properties file for Test environment. If we do not provide this, by default application.properties file is loaded. Else we can use:
@TestPropertySource("classpath:application-test.properties")
- Create Spring Container that uses internally WebApplication Support(DispatcherServlet):-
@SpringBootTest(webEnvironment = WebEnvironment.MOCK)
. It creates by default:AnnotationConfigServletWebApplicationContext
- Create required objects inside the container:- DataSource, HandlerMapping, ORM Config (EntityManagerFactory, EntityManager), etc. It can be implemented using:
@AutoConfigureMockMvc
For the final runtime environment reference is given by MockMvc
. That supports Test Dispatcher Servlet, Access Spring Container, execution of RestControllers, Database Connection support etc.
Todo Unit Test coding follow the below steps:-
- Create one Dummy/proxy(not made by the client) HTTP Request.
- Execute the dummy request using MockMvc and get the result(MvcResult).
- Read the response from the result object.
- Assert Response Data(checking Status, Body/content, header type e.t.c).
{"empName":"A","empSal":2500.0,"empMail":"[email protected]"}
Database dumps are used for Mock Testing, not the production or UAT env used.
@SpringBootTest(webEnvironment = WebEnvironment.MOCK)
@AutoConfigureMockMvc
@TestPropertySource("classpath:application-test.properties")
public class MiniProjectApplicationTests {
@Autowired
private MockMvc mockMvc;
@Test
public void testSaveOp() throws Exception {
// 1. prepare http request
MockHttpServletRequestBuilder request =
MockMvcRequestBuilders.post("/employee/update")
.contentType("application/json")
.content("{\"empName\":\"A\",\"empSal\":2500.0,\"empMail\":\"[email protected]\"}");
// 2. execute request and get result
MvcResult result = mockMvc.perform(request).andReturn();
// 3. Read Response from result
MockHttpServletResponse response = result.getResponse();
// 4. assert/validate result
assertEquals(HttpStatus.CREATED.value(), response.getStatus());
assertNotNull(response.getContentAsString());
}
}
Examples for different request construction:-
/employee/save (POST)
MockHttpServletRequestBuilder request =
MockMvcRequestBuilders
.post("/employee/update")
.contentType("application/json")
.content("{\"empName\":\"A\",\"empSal\":2500.0,\"empMail\":\"[email protected]\"}");
/employee/all (GET)
MockHttpServletRequestBuilder request =
MockMvcRequestBuilders
.get("/employee/all")
.accept("application/json");
/employee/remove/10 (DELETE)
MockHttpServletRequestBuilder request =
MockMvcRequestBuilders.delete("/employee/remove/10");
/employee/find/10 (GET)
MockHttpServletRequestBuilder request =
MockMvcRequestBuilders
.get("/employee/find/10")
.accept(MediaType.APPLICATION_XML);
/employee/update (PUT)
MockHttpServletRequestBuilder request =
MockMvcRequestBuilders
.put("/employee/update")
.contentType("application/json")
.content("{\"empName\":\"A\",\"empSal\":2500.0,\"empMail\":\"[email protected]\"}");
If you enjoyed this post, share it with your friends. Do you want to share more information about the topic discussed above or do you find anything incorrect? Let us know in the comments. Thank you!