侧边栏壁纸
博主头像
DJ's Blog博主等级

行动起来,活在当下

  • 累计撰写 133 篇文章
  • 累计创建 51 个标签
  • 累计收到 0 条评论

目 录CONTENT

文章目录

【Testing】Spring

Administrator
2022-04-05 / 0 评论 / 0 点赞 / 58 阅读 / 4476 字

#【Testing】Spring

@RunWith(SpringRunner.class)

@SpringBootTest

@TestPropertySource

@TestPropertySource是一个类级别的注解,可以用来加载自定义配置文件。
默认情况下,@TestPropertySource会加载resource目录下面和测试类同包路径下面的类名.properties配置文件
也可以通过location属性来自定义配置文件地址和名称,properties属性来自定义某些配置属性的值

@RunWith(SpringRunner.class)
@ContextConfiguration(classes = ClassUsingProperty.class)
// 自定义配置文件的地址,并且自定义某些配置属性的值
@TestPropertySource(locations = "/other-location.properties", properties = {"baeldung.testpropertysource.one=other-properties-value"})
public class PropertiesTestPropertySourceIntegrationTest {
    @Autowired[]()
    ClassUsingProperty classUsingProperty;
    @Test
        String output = classUsingProperty.retrievePropertyOne();
    public void givenDefaultTestPropertySource_whenVariableOneRetrieved_thenValueInDefaultFileReturned() {

        assertThat(output).isEqualTo("other-properties-value");
    }
}

@ContextConfiguration

@WebAppConfiguration

@MockMvc

MockMvc的局限

@TestConfiguration

静态内部类

@Import

@MockBean

@DataJpaTest

@DataJpaTest为测试持久层提供了一些标准的配置:

  1. 配置了一个内存数据库H2
  2. 配置了Hibernate,Spring Data,和对应的DataSource
  3. 执行了@EntityScan
  4. 打开SQL日志
@RunWith(SpringRunner.class)
@DataJpaTest
public class EmployeeRepositoryIntegrationTest {

    /** 标准JPA EntityManager的替代,提供了很多方法用来操作实体 */
    @Autowired
    private TestEntityManager  entityManager;
    
    @Autowired
    private EmployeeRepository employeeRepository;
    
    /**
     * 测试EmployeeRepository的findAll方法
     */
    @Test
    public void givenSetOfEmployees_whenFindAll_thenReturnAllEmployees() {
        // given
        Employee alex = new Employee("alex");
        Employee ron = new Employee("ron");
        Employee bob = new Employee("bob");
        entityManager.persist(alex);
        entityManager.persist(bob);
        entityManager.persist(ron);
        entityManager.flush();
        // when
        List<Employee> allEmployees = employeeRepository.findAll();
        // then
        assertThat(allEmployees)
	        .hasSize(3)
	        .extracting(Employee::getName)
	        .containsOnly(alex.getName(), ron.getName(), bob.getName());
    }
}

@WebMvcTest

@WebMvcTest注解会为我们的单元测试自动配置Spring MVC的基础设施。
大部分情况下,@WebMvcTest注解将仅限于引导单个Controller。
@WebMvcTest还会自动配置MockMvc,所以在单元测试类中直接通过@Autowired注解来注入一个MockMvc

@RunWith(SpringRunner.class)
@WebMvcTest(value = EmployeeRestController.class, excludeAutoConfiguration = SecurityAutoConfiguration.class)
public class EmployeeControllerIntegrationTest {

    @Autowired
    private MockMvc         mvc;

    @MockBean
    private EmployeeService service;
   
    /**
     * 测试EmployeeRestController的getAllEmployees方法
     * @throws Exception
     */
    @Test
    public void givenEmployees_whenGetEmployees_thenReturnJsonArray() throws Exception {
        // given
        Employee alex = new Employee("alex");
        Employee john = new Employee("john");
        Employee bob = new Employee("bob");
        List<Employee> allEmployees = Arrays.asList(alex, john, bob);
        given(service.getAllEmployees()).willReturn(allEmployees);
        // when
        ResultActions resultActions = mvc.perform(get("/api/employees").contentType(MediaType.APPLICATION_JSON));
        // then
        resultActions.andExpect(status().isOk())
	        // 打印接口请求和返回信息
	        .andDo(print())
	        .andExpect(jsonPath("$", hasSize(3)))
	        .andExpect(jsonPath("$[0].name", is(alex.getName())))
            .andExpect(jsonPath("$[1].name", is(john.getName())))
            .andExpect(jsonPath("$[2].name", is(bob.getName())));
        verify(service, times(1)).getAllEmployees();
        reset(service);
    }
}
0

评论区