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 :

  • RANDOM_PORT: This is providing the real environment. The embedded SERVER is started and listen on a random port. This is the ONE should be used for the integration test
  • DEFINED_PORT: Loads a WebServerApplicationContext and provides a real web environment.

These TWO modes are important from an Integration point of view, other modes supported are :

  • MOCK: This is the default mode. Here it  loads a web ApplicationContext and provides a mock environment
  • NONE: Loads an ApplicationContext by using SpringApplication but does not provide any web environment

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 &AMP; @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")));    } }


Discussion

No Comment Found