- 加载测试专用配置
- 案例演示
- 编写ConfigrationTest.java
- 编写MsgConfig.java
- 小结
- 测试类中启动web环境
- 案例演示
- 编写xml
- 编写WebTest.java
- 测试运行
- 小结
- 发送虚拟请求
- 案例模拟
- 新建UserController.java
- 运行测试
- 案例模拟2
- 编写WebTest.java
- 测试运行
- 小结
案例演示 编写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;
@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;
@SuppressWarnings({"all"})
@Configuration
public class MsgConfig {
@Bean
public String msg(){
return "bean msg";
}
}
小结
测试类中启动web环境
案例演示 编写xml只需要一个webEnvironment类就能让我们的测试类启动起来web环境
进而可以让我们进行web相关接口的测试
编写WebTest.javastarter后面加个web,刷新maven即可
package com.taotao;
import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;
@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;
@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;
@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);
}
}
测试运行
小结



