文章目录
加载测试专用配置
有效解决配置冲突问题
案例演示
编写ConfigrationTest.java
package com.taotao;
import com.taotao.config.MsgConfig;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.context.annotation.Import;
/**
* create by 刘鸿涛
* 2022/5/21 18:20
*/
@SuppressWarnings({"all"})
@SpringBootTest
@Import({MsgConfig.class})
public class ConfigrationTest {
@Autowired
private String msg;
@Test
void testConfiguration(){
System.out.println(msg);
}
}
编写MsgConfig.java
package com.taotao.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
/**
* create by 刘鸿涛
* 2022/5/21 18:19
*/
@SuppressWarnings({"all"})
@Configuration
public class MsgConfig {
@Bean
public String msg(){
return "bean msg";
}
}
小结
测试类中启动web环境
只需要一个webEnvironment类就能让我们的测试类启动起来web环境
进而可以让我们进行web相关接口的测试
案例演示
编写xml
starter后面加个web,刷新maven即可
编写WebTest.java
package com.taotao;
import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;
/**
* create by 刘鸿涛
* 2022/5/21 19:41
*/
@SuppressWarnings({"all"})
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT) //随机端口
public class WebTest {
@Test
void test(){
}
}
测试运行
小结
发送虚拟请求
案例模拟
新建UserController.java
package com.taotao.controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
/**
* create by 刘鸿涛
* 2022/5/21 21:29
*/
@SuppressWarnings({"all"})
@RestController
@RequestMapping("/Users")
public class UserController {
@GetMapping
public String getById(){
System.out.println("getById is running");
return "springboot";
}
}
运行测试
案例模拟2
编写WebTest.java
package com.taotao;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.request.MockHttpServletRequestBuilder;
import org.springframework.test.web.servlet.request.MockMvcRequestBuilders;
/**
* create by 刘鸿涛
* 2022/5/21 19:41
*/
@SuppressWarnings({"all"})
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT) //随机端口
@AutoConfigureMockMvc
public class WebTest {
@Test
void test(){
}
@Test
void testWeb(@Autowired MockMvc mvc) throws Exception {
//创建虚拟请求,当前访问/Users
MockHttpServletRequestBuilder builder = MockMvcRequestBuilders.get("/Users");
//执行对应的请求
mvc.perform(builder);
}
}