单元测试
SpringBootTest单元测试实战 简介:讲解SpringBoot的单元测试 1. 引入相关依赖
<dependency>
<groupId>org.springframework.boot
</groupId>
<artifactId>spring-boot-starter-test
</artifactId>
<scope>test
</scope>
</dependency>
2. 使用
@RunWith(SpringRunner
.class)
@SpringBootTest(classes
={XdclassApplication
.class})
public class SpringBootTests { }
示例
import junit
.framework
.TestCase
;
import org
.junit
.After
;
import org
.junit
.Before
;
import org
.junit
.Test
;
import org
.junit
.runner
.RunWith
;
import org
.springframework
.boot
.test
.context
.SpringBootTest
;
import org
.springframework
.test
.context
.junit4
.SpringRunner
;
@RunWith(SpringRunner
.class)
@SpringBootTest(classes
={LhwClassApplication
.class})
public class SpringBootTestDemo {
@Test
public void testOne(){
System
.out
.println("test hello 1");
TestCase
.assertEquals(1, 1);
}
@Test
public void testTwo(){
System
.out
.println("test hello 2");
TestCase
.assertEquals(1, 1);
}
@Before
public void testBefore(){
System
.out
.println("before");
}
@After
public void testAfter(){
System
.out
.println("after");
}
}
测试api(使用mockMVC)
SpringBoot测试进阶高级篇之MockMvc讲解 简介:讲解MockMvc类的使用和模拟Http请求实战
1、增加类注解 @AutoConfigureMockMvc
@SpringBootTest(classes={XdclassApplication.class})
2、相关API
perform:执行一个RequestBuilder请求
andExpect:添加ResultMatcher->MockMvcResultMatchers验证规则
andReturn:最后返回相应的MvcResult->Response
示例
import org
.junit
.Test
;
import org
.junit
.runner
.RunWith
;
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
.context
.junit4
.SpringRunner
;
import org
.springframework
.test
.web
.servlet
.MockMvc
;
import org
.springframework
.test
.web
.servlet
.MvcResult
;
import org
.springframework
.test
.web
.servlet
.request
.MockMvcRequestBuilders
;
import org
.springframework
.test
.web
.servlet
.result
.MockMvcResultMatchers
;
@RunWith(SpringRunner
.class)
@SpringBootTest(classes
={LhwClassApplication
.class})
@AutoConfigureMockMvc
public class MockMvcTestDemo {
@Autowired
private MockMvc mockMvc
;
@Test
public void apiTest() throws Exception
{
MvcResult mvcResult
= mockMvc
.perform( MockMvcRequestBuilders
.get("/v1/test_request?id=20") ).
andExpect( MockMvcResultMatchers
.status().isOk() ).andReturn();
int status
= mvcResult
.getResponse().getStatus();
System
.out
.println(status
);
}
}