Spring Boot:单元测试

作者: 聪明的奇瑞 | 来源:发表于2018-01-24 14:12 被阅读311次

    单元测试

    单元测试注意事项

    • 测试方法必须用@Test修饰
    • 测试方法必须使用public void修饰,不能带参数
    • 一般使用单元测试会新建一个test目录存放测试代码,在生产部署时只要将test代码目录删除即可
    • 测试代码的包应该和被测试代码的包结构一致
    • 测试单元中的每个方法必须可以独立测试,方法间不能有任何依赖
    • 测试类一般用Test作为类名后缀
    • 测试放一般使用test作为方法名前缀

    常用注解

    • @Test:将一个普通方法修饰称一个测试方法
      • @Test(excepted==xx.class) 忽略某异常类
      • @Test(timeout=毫秒数) 测试方法执行时间是否符合预期
    • @BeforeClass:会在所有方法执行前执行
    • @Afterclass:会在所有方法执行后执行
    • @Before:在每一个测试方法被运行前执行一次
    • @After:在每一个测试方法运行后执行一次
    • @Ignore:修饰的方法会被测试运行器忽略
    • @RunWith:更改测试运行器
      • @RunWith(SpringRunner.class)

    Spring Boot 单元测试

    • Spring Boot 提供了两个包来支持单元测试:
      • spring-boot-test:包含测试的核心
      • spring-boot-test-autoconfigure:用来支持测试的自动配置

    配置相关注解

    @SpringBootTest

    • 它能够测试 SpringApplication,因为 SpringBoot 程序入口是SpringApplication,基本所有配置都会通过入口类去加载,也可以通过 classes 属性设置应用程序入口类,webEnvironment 可以设置 web 测试环境,可选属性有:
      • MOCK:提供一个模拟的Servlet环境,内置的Servlet容器没有启动,配合@AutoConfigureMockMvc使用
      • RANDOM_PORT:提供真实的Servlet环境,启动内置容器,随即端口
      • DEFINED_PORT:配置真实Servlet环境,使用默认端口
      • NONE:提供跟Mock一样不真实的Servlet环境

    @LocalServerPort

    • 注解在属性上,注入端口号

    @ActiveProfiles(profiles = "test")

    • 指定多环境测试时的环境配置

    @Slf4j

    • 如果不想每次都写下面代码可以用注解@Slf4j
    private  final Logger logger = LoggerFactory.getLogger(XXX.class); 
    

    @AutoConfigureMockMvc

    • 配合 @SpringBootTest 注入一个 MockMvc 实例

    @WebAppConfiguration

    • 声明一个用于测试的 ApplicationContext 来模拟 ServletContext

    测试例子

    测试 REST 接口

    • 测试 REST 接口可以配合 TestRestTemplate
    @RunWith(SpringRunner.class)
    @SpringBootTest(classes = Application.class,webEnvironment = WebEnvironment.RANDOM_PORT)
    public class RandomPortExampleTests {
    
        @Autowired
        private TestRestTemplate restTemplate;
    
        @Test
        public void exampleTest() {
            String body = this.restTemplate.getForObject("/", String.class);
            assertThat(body).isEqualTo("Hello World");
        }
    }
    

    测试 Spring MVC

    • 测试 SpringMVC Controller 可以使用 @WebMvcTEst,它会自动配置 MockMvc,Mock MVC 提供了一种方法来测试 MVC Controller,而不用启动完整的 HTTP Server
    @Slf4j
    @RunWith(SpringRunner.class)
    @SpringBootTest(classes = Application.class)
    @AutoConfigureMockMvc
    public class SessionControllerTest {
    
        @Autowired
        private MockMvc mvc;
    
        private ObjectMapper objectMapper = new ObjectMapper();
    
        @Test
        public void testLogin() throws Exception {
            LoginDTO loginDTO = new LoginDTO();
            loginDTO.setUsername("linyuan");
            loginDTO.setPassword("123456");
            byte[] body = objectMapper.writeValueAsBytes(loginDTO);
            String resp = this.mvc.perform(
                    post("/session")              //请求的URL
                            .content(body)                   //请求的数据
                            .param("请求的参数名","参数值")          //请求的参数
                            .contentType(MediaType.APPLICATION_JSON)    //请求数据的格式
                            .accept(MediaType.APPLICATION_JSON)         //接收返回数据的格式
            ).andExpect(status().isOk())                     //验证执行结果状态码
             .andDo(print())                                 //请求结果处理,输出请求结果
             .andReturn().getResponse().getContentAsString();       //最后返回的结果,将数据转换为字符串
            System.out.println(resp);
        }
    
    }
    

    ----- 持续更新中 -----

    相关文章

      网友评论

        本文标题:Spring Boot:单元测试

        本文链接:https://www.haomeiwen.com/subject/rvluaxtx.html