美文网首页
springboot 单元测试(如何使用基于web的单元测试?)

springboot 单元测试(如何使用基于web的单元测试?)

作者: dylan丶QAQ | 来源:发表于2021-04-17 19:32 被阅读0次

spring的测试环境是我们在开发过程中必须要掌握的,测试 有的时候需要测试cotroller,有的时候需要测试service的内容,和大家分享一下如何在工作中进行测试的,立志工具人。一起干饭!


本章主要内容

  • 测试运行器
  • 测试控制器

1.测试运行器

测试是软件开发的重要组成部分,一般情况下,测试的时候,我们只需要模拟请求数据,将数据填充至测试方法中,然后启动spring容器,即可。

@Slf4j
@RunWith(SpringRunner.class)
@SpringBootTest
public class Test1 {
    @Test
    public void contextLoads() {

    }
}

类中的内容并不多:这个类只有一个空的测试方法。即便是空的,系统还是会执行必要的检查,确保spring应用上下文能够成功加载。

  • @RunWith(SpringRunner.class)
    @RunWith是JUnit的注解,它会提供一个测试运行器(runner)来指导JUnit如何运行测试。这个例子中,为JUnit提供的是SpringRunner,这是一个spring提供的测试运行器,它会创建测试运行所需的spring应用上下文。(SpringRunner 是SpringJUnit4ClassRunner的别名,是在spring4.3中引入的,以便于移除对特定JUnit版本的关联)
  • @SpringBootTest 会告诉JUnit在启动测试的时候要添加上SpringBoot的所有功能。可以把这个测试类看做 在main()方法中调用SpringApplication.run()。

2.测试控制器

对于控制器的测试,我们平常并不是很经常用到。它与上面的测试有所不同,没有使用@SpringBootTest标记,而是添加了@WebMvcTest注解。这是Spring boot所提供的特殊测试注解,他会让这个测试在Spring MVC 应用上下文中执行。更具体来讲,它会将HomeControlelr 注册到SpringMVC中,这样的话,我们就可以向他发送请求了。

package com.ptdot.portal.controller;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.test.web.servlet.MockMvc;

import static org.hamcrest.Matchers.containsString;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.view;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content;

/**
 * @ClassName HomeControllerTest
 * @Description TODO
 * @Author liulinfang
 * @Date 2021/4/17 19:05
 * @Version 1.0
 */
@RunWith(SpringRunner.class)
@WebMvcTest(HomeController.class)
public class HomeControllerTest {

    @Autowired
    private MockMvc mockMvc;
    
    @Test
    public void testHomePage() throws  Exception {
//        发起对"/"的get请求
        mockMvc.perform(get("/"))
//                期望得到HTTP200
                .andExpect(status().isOk())
//                期望得到home视图
                .andExpect(view().name("home"))
//                期望包含"Welcome to ..."
                .andExpect(content().string(containsString("Welcome to ...")));
    }
}

  • @WebMvcTest同样会为测试SpringMVC应用提供Spring环境支持。尽管我们可以启动一个服务器来进行测试,但是对于一定的场景来说,仿造一个SpringMVC的运行机制就可以。这里主要是注入了MockMvc,能够让测试实现mockup。
  • 通过testHomePage()方法,我们定义了针对Home想要执行的测试。它首先使用MockMvc对象对"/"发起HTTP GET 请求。对于这个请求,我们设置了如下的预期:
    • 响应具备HTTP200状态
    • 视图的逻辑名称应该是home
    • 渲染后的视图应该包含文本 "Welcome to ..."

不要以为每天把功能完成了就行了,这种思想是要不得的,互勉~!

若文章对您有用,请点赞支持哦。

相关文章

网友评论

      本文标题:springboot 单元测试(如何使用基于web的单元测试?)

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