Spring Boot 测试

Spring Boot 测试

1. 添加pom测试依赖

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-test</artifactId>
    <scope>test</scope>
</dependency>

2. 测试类

// 在测试环境中转配,装配的Bean只会在测试环境中使用
@TestConfiguration
public class MyTestConfiguration {

    @Bean
    public Runnable create() {
        return () -> {
        };
    }
}


@RunWith(SpringRunner.class)
// 指定在测试环境中装配的配置类
@SpringBootTest(classes = MyTestConfiguration.class)
public class DictDaoTest {
    @Autowired
    private DictDao dictDao;
    @Autowired
    private ApplicationContext context;

    @Test
    public void testList() {
        List<Map<String, Object>> result = dictDao.list();
        for (Map<String, Object> map : result) {
            System.out.println(map);
        }
        Assert.assertNotNull(context.getBean(Runnable.class));
    }

}

注意: Spring Boot 会优先使用测试环境的配置文件,如果没有才会使用正式的配置文件

3. 测试环境中使用配置项

@RunWith(SpringRunner.class)
// 测试环境中添加配置项,方式1
@SpringBootTest(properties = { "app.version=1.0.0" })
public class EnvironmentTest {
    @Autowired
    private ConfigurableEnvironment env;
    @Value("${app.version}")
    private String version;

    // 添加配置项,方式2
    @Before
    public void init() {
        TestPropertyValues.of("test.username=root").and("test.password=123456").applyTo(env);
    }

    @Test
    public void test() {
        Assert.assertEquals("1.0.0", env.getProperty("app.version"));
        Assert.assertEquals("1.0.0", version);
        Assert.assertEquals("root", env.getProperty("test.username"));
        Assert.assertEquals("123456", env.getProperty("test.password"));

    }
}

4. Controller 测试

@RestController
public class StudentController {

    @GetMapping("student/{id}")
    public String get(@PathVariable("id") Long id) {
        return "student" + id;
    }

    @GetMapping("student/list")
    public String list() {
        return "student";
    }
}

1. 测试Restful接口

@RunWith(SpringRunner.class)
//不需要启动Spring Boot服务,但需要指定本处使用的端口方式
@SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT)
public class StudentControllerTest {
    //Rest测试模板类
    @Autowired
    private TestRestTemplate restTemplate;

    @Test
    public void testGet() {
        String result = restTemplate.getForObject("/student/100", String.class);
        Assert.assertEquals("student100", result);
    }

    @Test
    public void testList() {
        String result = restTemplate.getForObject("/student/list", String.class);
        Assert.assertEquals("student", result);
    }

}

2. 使用Mock测试WebController

注意:

@WebMvcTest 只能测试Controller,Controller中不能依赖注入其他Bean,原因是:这种方式不会加载Spring 容器

@RunWith(SpringRunner.class)
// WebMvc测试方式,需要指定测试的Controller。不需要在Web环境下运行
@WebMvcTest(controllers = { StudentController.class })
public class StudentControllerMvcTest {

    @Autowired
    private MockMvc mvc;

    @Test
    public void testGet() throws Exception {
        mvc.perform(MockMvcRequestBuilders.get("/student/100"))//
                .andExpect(MockMvcResultMatchers.status().isOk()) // 匹配结果状态码为200
                .andExpect(MockMvcResultMatchers.content().string("student100"));// 匹配返回结果

    }

    @Test
    public void testList() throws Exception {
        mvc.perform(MockMvcRequestBuilders.get("/student/list").param("name", "张三"))//
                .andExpect(MockMvcResultMatchers.status().isOk())//
                .andExpect(MockMvcResultMatchers.content().string("student"));
    }
}

3. 使用Mock方式测试WebController

注意:

@SpringBootTest 注解使用时会加载Spring容器,但是不会自动注入MockMvc对象,需要配合@AutoConfigureMockMvc注解,自动注入MockMvc对象。这两个注解不能和@WebMvcTest注解同时使用

@RunWith(SpringRunner.class)
@SpringBootTest
@AutoConfigureMockMvc
public class StudentControllerMvcTest {

    @Autowired
    private MockMvc mvc;

    @Test
    public void testGet() throws Exception {
        mvc.perform(MockMvcRequestBuilders.get("/student/100"))//
                .andExpect(MockMvcResultMatchers.status().isOk()) // 匹配结果状态码为200
                .andExpect(MockMvcResultMatchers.content().string("student100"));// 匹配返回结果

    }

    @Test
    public void testList() throws Exception {
        mvc.perform(MockMvcRequestBuilders.get("/student/list").param("name", "张三"))//
                .andExpect(MockMvcResultMatchers.status().isOk())//
                .andExpect(MockMvcResultMatchers.content().string("student"));
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值