How to do it...

Let us implement test cases in Spring Boot 2.0 projects by performing the following steps:

  1. First, add the Spring Test starter POM in the pom.xml file:
        <dependency> 
            <groupId>org.springframework.boot</groupId> 
            <artifactId>spring-boot-starter-test</artifactId> 
            <scope>test</scope> 
        </dependency>
  1. This application is secured by Spring Security, so add the following Spring Security Test module to the application in order to utilize some mock-related annotations useful during testing:
        <dependency> 
            <groupId>org.springframework.security</groupId> 
            <artifactId>spring-security-test</artifactId> 
            <version>4.2.2.BUILD-SNAPSHOT</version> 
            <scope>test</scope> 
        </dependency> 
  1. To test the Spring Boot 2.0 controller methods, add the following SpringTestContext class insideorg.packt.secured.mvc.test of src/test/java with an emphasis on the new annotations, @SpringBootTest and @AutoConfigureMockMvc:
        import static org.springframework.security.test.web.servlet.request.
SecurityMockMvcRequestPostProcessors.user; import static org.springframework.test.web.servlet.request.
MockMvcRequestBuilders.get; import static org.springframework.test.web.servlet.result.
MockMvcResultHandlers.print; import static org.springframework.test.web.servlet.result.
MockMvcResultMatchers.status; @RunWith(SpringRunner.class) @SpringBootTest @AutoConfigureMockMvc @ContextConfiguration(classes={ HRBootApplication.class, SpringContextConfig.class, SpringAsynchConfig.class }) public class TestControllers { @Autowired private MockMvc mvc; @Test public void callEmpFormReq() throws Exception { mvc.perform(get("/react/empform.html") .with(user("sjctrags") .password("sjctrags").roles("USER"))) .andDo(print()) .andExpect(status().isOk()); } }
  1. To simply test the JDBC, DAO, and service layers, add the following @SpringBootTest class inside the same org.packt.spring.boot.test package:
import static org.junit.Assert.*; 
@RunWith(SpringRunner.class) 
@SpringBootTest 
@ContextConfiguration(classes={ HRBootApplication.class,  
   SpringContextConfig.class, SpringAsynchConfig.class }) 
public class TestDaoLayer { 
 
@Autowired 
private DepartmentDao departmentDaoImpl; 
    
@Test 
public void testDeptDao(){ 
assertNotNull(departmentDaoImpl.getDepartments()); 
System.out.println( 
departmentDaoImpl.getDepartments()); 
} 
} 
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.15.3.167