InterviewSolution
| 1. |
How can you do the Integration Test with Spring Boot? |
|
Answer» You can use @SpringBootTest annotation. This is over and above the spring-test module. When you include @SpringBootTest, applicationContext is started. @RunWith(SpringRunner.class) @SpringBootTest public class YourTestClass {SpringBootTest supports different modes, you can enable anyone of them by using web environment property along with @SpringBootTest. These modes are :
These TWO modes are important from an Integration point of view, other modes supported are :
For example, if you go for RANDOM_PORT, code will look LIKE : @RunWith(SpringRunner.class) @SpringBootTest(web environment = SpringBootTest.WebEnvironment.RANDOM_PORT) public class YourTestClass @MockBean : You can make use of @MockBean to mock a particular service or repository or some bean. For example, RunWith(SpringRunner.class) @SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT) public class YourTestClass { @MockBean private EmployeeRepository employeeRepository; @Autowired private EmployeeService employeeService; @Test public void testRetrieveStudentWithMockRepository() throws Exception { Optional<Employee> employee = Optional.of( new Employee(1,"Scott")); when(employeeRepository.findById(49)).thenReturn(employee); assertTrue(employeeService.retrieveStudent(49).getName().contains("Scott")); } }Using MockMvc & @AutoConfigureMockMvc: You can mock up the http requests using MockMvc & @AutoConfigureMockMvc For example, @RunWith(SpringRunner.class) @SpringBootTest @AutoConfigureMockMvc public class YourTestClass { @Autowired private MockMvc mockMvc; @Test public void testMethod() throws Exception { this.mockMvc.perform(post("/employees")).andExpect(status().is2xxSuccessful()); this.mockMvc.perform(get("/employee/49")).andDo(print()).andExpect(status().isOk()) .andExpect(content().string(containsString("Rahul"))); } } |
|