springboot单元测试和api测试

mac2024-04-04  34

单元测试
SpringBootTest单元测试实战 简介:讲解SpringBoot的单元测试 1. 引入相关依赖 <!--springboot程序测试依赖,如果是自动创建项目默认添加--> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> </dependency> 2. 使用 @RunWith(SpringRunner.class) //底层用junit SpringJUnit4ClassRunner @SpringBootTest(classes={XdclassApplication.class})//启动整个springboot工程 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) //底层用junit SpringJUnit4ClassRunner @SpringBootTest(classes={LhwClassApplication.class})//启动整个springboot工程 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; /** * 功能描述:测试mockmvc类 * * <p> 创建时间:Apr 24, 2018 10:01:12 PM </p> * <p> 作者:小D课堂</p> */ @RunWith(SpringRunner.class) //底层用junit SpringJUnit4ClassRunner @SpringBootTest(classes={LhwClassApplication.class}) //启动整个springboot工程 @AutoConfigureMockMvc //帮助我们配置mockmvc public class MockMvcTestDemo { @Autowired private MockMvc mockMvc; // mockMvc测试api的单元测试工具 @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); } }
最新回复(0)