boot spring test 文档_Spring Boot Test 入门

Spring Boot Test入门

pom文件

需要在项目根目录下pom.xml文件,添加spring boot test依赖的jar包:

org.springframework.boot

spring-boot-starter-test

test

Service单元测试

创建测试类,在测试类的类头部添加:@RunWith(SpringRunner.class)和@SpringBootTest注解,在测试方法的前添加@Test,最后选择方法右键run运行。

使用@Autowired注入需要测试的类。

示例:

@RunWith(SpringRunner.class)

@SpringBootTest

public class StudentServiceTest {

@Autowired

private StudentService studentService;

@Test

public void getStudent() throws Exception {

Student student = studentService.getStudent("1001");

Assert.assertEquals(16, student.getAge());

}

}

Controller单元测试

创建测试类,在测试类的类头部添加:@RunWith(SpringRunner.class)、@SpringBootTest、@ AutoConfigureMockMvc注解,在测试方法的前添加@Test,最后选择方法右键run运行。

使用@Autowired 注入MockMvc,在方法中使用 mvc测试功能。

示例:

@RunWith(SpringRunner.class)

@SpringBootTest

@AutoConfigureMockMvc

public class StudentControllerTest {

@Autowired

private MockMvc mvc;

@Test

public void getAll() throws Exception {

mvc.perform(MockMvcRequestBuilders.get("/student/getAll"))

.andExpect(MockMvcResultMatchers.model().attributeExists("students"));

}

@Test

public void save() throws Exception {

Student student = new Student();

student.setAge(12);

student.setId("1003");

student.setName("hehe");

mvc.perform(MockMvcRequestBuilders.post("/student/save", student));

}

@Test

public void delete() throws Exception {

mvc.perform(MockMvcRequestBuilders.delete("/student/delete?id=1002"));

}

@Test

public void index() throws Exception {

mvc.perform(MockMvcRequestBuilders.get("/student/index")).andReturn();

}

}

注意:spring boot 版本是基于 1.4.7.RELEASE

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值