Spring boot 测试类详解 Junit

Spring boot 项目测试类详解

测试类实例

@RunWith(SpringJUnit4ClassRunner.class) 
@SpringApplicationConfiguration(classes = HelloApplication.class) 
@WebAppConfiguration
public class HelloApplicationTests ( 
     private MockMvc mvc; 
	
	@Before 
    public void setOp() throws Exception { 
			mvc = MockMvcBuilders. standaloneSetup (new HelloController ()) . build() ; 
	}
	
	@Test 
	public void hello() throws Exception { 
			mvc.perform(MockMvcRequestBuilders.get("/hello") .accept(MediaType. 
				APPLICATION_JSON)) .andExpect(status() .isOk())
 				.andExpect (content() . string (equal To ("Hello World"))); 
 	}

代码解析如下

• @RunWith(SpringJUnit4ClassRunner.class): 引入Spring对JUnit4的支持。
• @SpringApplicationConfiguration (classes = HelloApplication.class): 指定Spring Boot的启动类。
• @WebAppConfiguration: 开启Web应用的配置, 用于模拟ServletContext。
• MockMvc对象: 用于模拟调用 Controller的接口发起请求, 在@Test定义的hello测试用例中, perform函数执行 一次请求调用, accept用于执行接收的数据类型,andExpect用于判断接口返回的期望值。
• @Before: JUnit中定义在测试用例@Test内容执行前预加载的内容, 这里用来初始化对HelloController的模拟 。

注意引入下面的静态引用, 让status、 content、 equalTo函数可用:
import static org.hamcrest.Matchers.equalTo;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.
content;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.
status;

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值