`

Spring boot junit test

 
阅读更多

Refer to:

https://www.baeldung.com/spring-boot-testing

a. JUnit test 的类型以及如何取舍:

 Unit tests that can run in isolation as well as integration tests that will bootstrap Spring context before executing tests. 两种,isolation, integration test. Ideally, we should keep the integration tests separated from the unit tests and should not run along with the unit tests.The integration tests need to start up a container to execute the test cases.

b. 关于Integration Test

   The @SpringBootTest annotation can be used when we need to bootstrap the entire container. The annotation works by creating the ApplicationContext that will be utilized in our tests.

 

 

@RunWith(SpringRunner.class) is used to provide a bridge between Spring Boot test features and JUnit,Whenever we are using any Spring Boot testing features in our JUnit tests, this annotation will be required.

1.Test Dao(reposotory层) : DataJpaTest 可以自动生成内存数据库,下面这个EntityManager是用的TestEntityManager, 可以很方便的把数据先插入到数据库中。JPA可以方便的自动生成 H2结构,并方便的插入数据,那么mybatis 怎么办呢?

 

 

@Test
public void whenFindByName_thenReturnEmployee() {
    // given
    Employee alex = new Employee("alex");
    entityManager.persist(alex);
    entityManager.flush();
 
    // when
    Employee found = employeeRepository.findByName(alex.getName());
 
    // then
    assertThat(found.getName())
      .isEqualTo(alex.getName());
}

 2. Test service层

 

Ideally, we should be able to write and test our Service layer code without wiring in our full persistence layer.

2.1   使用 @TestConfiguration 重新生成Service(只在Test环境中有效),重新生成的Service中Mock repository 层

2.2 @MockBean. It creates a Mock for the EmployeeRepository which can be used to bypass the call to the actual EmployeeRepository:

 

@RunWith(SpringRunner.class)
public class EmployeeServiceImplIntegrationTest {
 
    @TestConfiguration
    static class EmployeeServiceImplTestContextConfiguration {
  
        @Bean
        public EmployeeService employeeService() {
            return new EmployeeServiceImpl();
        }
    }
 
    @Autowired
    private EmployeeService employeeService;
 
    @MockBean
    private EmployeeRepository employeeRepository;
 
    // write test cases here
}

 

@Before
public void setUp() {
    Employee alex = new Employee("alex");
 
    Mockito.when(employeeRepository.findByName(alex.getName()))
      .thenReturn(alex);
}

 3. Controller 层:Mock Service层

To test the Controllers, we can use @WebMvcTest. It will auto-configure the Spring MVC infrastructure for our unit tests.

In most of the cases, @WebMvcTest will be limited to bootstrap a single controller. It is used along with @MockBean to provide mock implementations for required dependencies.

@WebMvcTest also auto-configures MockMvc which offers a powerful way of easy testing MVC controllers without starting a full HTTP server.

@RunWith(SpringRunner.class)
@WebMvcTest(EmployeeRestController.class)
public class EmployeeRestControllerIntegrationTest {
 
    @Autowired
    private MockMvc mvc;
 
    @MockBean
    private EmployeeService service;
 
    // write test cases here
}

 

@Test
public void givenEmployees_whenGetEmployees_thenReturnJsonArray()
  throws Exception {
     
    Employee alex = new Employee("alex");
 
    List<Employee> allEmployees = Arrays.asList(alex);
 
    given(service.getAllEmployees()).willReturn(allEmployees);
 
    mvc.perform(get("/api/employees")
      .contentType(MediaType.APPLICATION_JSON))
      .andExpect(status().isOk())
      .andExpect(jsonPath("$", hasSize(1)))
      .andExpect(jsonPath("$[0].name", is(alex.getName())));
}

 

 

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics