5-SpringBoot单元测试

SpringBoot 的单元测试

当用户创建一个spring boot 项目时会默认创建测试类 ,并且所有springboot 项目都添加了 spring-boot-starter-test 依赖

!

注解解释

@RunWith() SpringRunner 是spring framework 中 SpringJUnit4ClassRunne 的别名

@Spring BootTest 除了提供spring testcontext 应用上下文,还提供了contextloader ,自动搜索springbootconfiguration ,还提供了自定义环境属性为不同的webEnvironment 模式提供支持

webEnvironment 主要有四种

  • MOCK 这个时候当类路径下存在servlet API的时候就会创建webapplicationcontext并提供一个mockservlet 环境 当类路径下存在spring WebFlux 的时候则创建ReactiveWebApplication 如果都没有 则创建常规的applicationcontext
  • RANDOM_PORT 这种模式将提供一个真实的servlet 环境使用内嵌的容器但是端口随机
  • DEFINED_PORT 提供一个真实的servlet 环境 使用内嵌的环境和定义的接口
  • NONE 这种模式只加载一个普通的ApplicationContext 不适用web测试

在spring 的测试中一般需要指定 @ContextConfiguration(class = ) 或者@ContextConfiguration(locations = )加载指定配置 ,但是springboot 中@test 注解会去包含测试类的包下 扫描带有 配置相关注解的类

junit 注解同样适用

@test 注解来自junit ,所以 junit 的注解 @After ,@before , @AfterClass @BeforeClass , @Ignore

注意 在junit 5.x中,@Before主键被@BeforeEach所替代,因此就不生效了

所以在使用高版本注解的时候 使用 org.junit.jupiter.api 包下的注解

Service 测试

service 测试就是常规测试

例如 service

@Service
public class TestService {

    public String hello(String name){
        return  "hello"+name;
    }
}

测试代码

@RunWith(SpringRunner.class)
@SpringBootTest
class DevtoolsdemoApplicationTests {

    @Test
    void contextLoads() {
    }

    @Autowired
    TestService testService;

    @Test
    void test(){
        String s = testService.hello("asdas");
        //这里使用了断言判断测试结果是否正确
        Assert.assertThat(s, Matchers.is("helloasdas"));
    }
}

Controller 测试

controller 测试要使用 mock 测试 springboot 提供了mockmvc 对HTTP 进行模拟

例如 controller

@RestController
public class TestController {


    @Autowired
    TestService testService;

    public Object test(){

        return testService.hello("aaaa");
    }
}

测试代码

@Autowired
    WebApplicationContext webApplicationContext;

    //MockMvc 不需要注入 通过 @before 初始化
    MockMvc mockMvc;

    @BeforeEach
    public void before(){
        mockMvc = MockMvcBuilders.webAppContextSetup(webApplicationContext).build();
    }

    @Test
    public void test() throws Exception {
        MvcResult result = mockMvc.perform(
                MockMvcRequestBuilders.get("/test")   //访问路径 及方法
                .contentType(MediaType.APPLICATION_FORM_URLENCODED)  //设置相应类型
                .param("name","aaaa")  //设置参数
        )
                .andExpect(MockMvcResultMatchers.status().isOk())   // 或 is(状态码)  检测状态码
                .andDo(MockMvcResultHandlers.print())  // 将详细信息打印到控制台
                .andReturn(); //返回相应的结果
        System.out.println(result.getResponse().getContentAsString());  //打印结果
    }

spring boot 还可以使用真实的servlet 环境测试

测试代码

@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.DEFINED_PORT)
public class TestTwo {

    @Autowired
    TestRestTemplate testRestTemplate;

    @Test
    public void test(){
        ResponseEntity<String> re = testRestTemplate.getForEntity("/test?name={0}", String.class, "mass");

        System.out.println(re.getStatusCode());
        System.out.println(re.getBody());
    }
}

这种方式 需要在 SpringBootTest 注解中开启(webEnvironment = SpringBootTest.WebEnvironment.DEFINED_PORT) 或者 (webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT) 这时候注入TestRestTemplate 对象测试即可

JSON测试

用户在测试时若要使用json可以在类上标注 @JsonTest 并在测试类中注入JacksonTester<要测试的类>

jacksontester.write(转化为json的类)  //转化为json
jacksontester.parseObject(content)  //转化为对象
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值