1、配置依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
2、基本使用
package com.vim.modules.controller;
import com.vim.Application;
import org.junit.*;
import org.junit.runner.RunWith;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
@RunWith(SpringRunner.class)
@SpringBootTest(classes={Application.class})
public class TestHomeController {
@Test
public void testOne(){
System.out.println("test hello 1");
}
@Test
public void testTwo(){
System.out.println("test hello 2");
}
/**
* 在所有测试方法前执行一次,一般在其中写上整体初始化的代码
*/
@BeforeClass
public static void testBeforeClass(){
System.out.println("beforeClass");
}
/**
* 在所有测试方法后执行一次,一般在其中写上销毁和释放资源的代码
*/
@AfterClass
public static void afterBeforeClass(){
System.out.println("afterClass");
}
/**
* 在每个测试方法前执行,一般用来初始化方法
*/
@Before
public void testBefore(){
System.out.println("before");
}
/**
* 在每个测试方法后执行,在方法执行完成后要做的事情
*/
@After
public void testAfter(){
System.out.println("after");
}
}
3、Mock 测试
- 控制器
package com.vim.modules.controller;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
@Controller
@RequestMapping(value = "/test")
public class HomeController {
@RequestMapping(value = "/test1")
@ResponseBody
public String test1(){
return "success";
}
@RequestMapping(value = "/test2")
public String test2(){
return "success";
}
}
- 测试类
package com.vim.modules.controller;
import com.vim.Application;
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.request.MockMvcRequestBuilders;
import org.springframework.test.web.servlet.result.MockMvcResultHandlers;
import org.springframework.test.web.servlet.result.MockMvcResultMatchers;
@RunWith(SpringRunner.class)
@SpringBootTest(classes={Application.class})
@AutoConfigureMockMvc
public class TestHomeController {
@Autowired
private MockMvc mvc;
@Test
public void testTest1() throws Exception{
mvc.perform(MockMvcRequestBuilders.get("/test/test1"))
.andExpect(MockMvcResultMatchers.status().isOk())
.andExpect(MockMvcResultMatchers.content().string("success"))
.andDo(MockMvcResultHandlers.print());
}
@Test
public void testTest2() throws Exception{
mvc.perform(MockMvcRequestBuilders.get("/test/test2"))
.andExpect(MockMvcResultMatchers.status().isOk())
.andExpect(MockMvcResultMatchers.view().name("success1"));
}
}