Controller 层的单元测试
创建一个用于测试的控制器(在main目录下)
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class HelloController {
@RequestMapping("/hello")
public String hello(String name) {
return "hello " + name;
}
}
编写测试(在test目录下)
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.http.MediaType;
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.MockMvcResultHandlers;
import org.springframework.test.web.servlet.result.MockMvcResultMatchers;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import org.springframework.web.context.WebApplicationContext;
@SpringBootTest
@RunWith(SpringRunner.class)
public class HelloControllerTest {
//启用web上下文
@Autowired
private WebApplicationContext webApplicationContext;
private MockMvc mockMvc;
@Before
public void setUp() throws Exception {
//使用上下文构建mockMvc
mockMvc = MockMvcBuilders.webAppContextSetup(webApplicationContext).build();
}
@Test
public void hello() throws Exception {
// 得到MvcResult自定义验证
// 执行请求
System.out.println("-------------------------------------------------------------------------------------------------");
MvcResult mvcResult = mockMvc.perform(MockMvcRequestBuilders.get("/hello")
//.post("/hello") 发送post请求
.contentType(MediaType.APPLICATION_JSON_UTF8)
//传入参数
.param("name", "XiaoYeQu")
// .accept(MediaType.TEXT_HTML_VALUE))
//接收的类型
.accept(MediaType.APPLICATION_JSON_UTF8))
//等同于Assert.assertEquals(200,status);
//判断接收到的状态是否是200
.andExpect(MockMvcResultMatchers.status().isOk())
//等同于 Assert.assertEquals("hello longzhonghua",content);
.andExpect(MockMvcResultMatchers.content().string("hello XiaoYeQu"))
.andDo(MockMvcResultHandlers.print())
//返回MvcResult
.andReturn();
//得到返回代码
int status = mvcResult.getResponse().getStatus();
//得到返回结果
String content = mvcResult.getResponse().getContentAsString();
//断言,判断返回代码是否正确
Assert.assertEquals(200, status);
//断言,判断返回的值是否正确
Assert.assertEquals("hello XiaoYeQu", content);
System.out.println("-------------------------------------------------------------------------------------------------");
}
}
输出以下结果:
-------------------------------------------------------------------------------------------------
MockHttpServletRequest:
HTTP Method = GET
Request URI = /hello
Parameters = {name=[XiaoYeQu]}
Headers = [Content-Type:"application/json;charset=UTF-8", Accept:"application/json;charset=UTF-8"]
Body = null
Session Attrs = {}Handler:
Type = com.jia.controller.HelloController
Method = com.jia.controller.HelloController#hello(String)Async:
Async started = false
Async result = nullResolved Exception:
Type = nullModelAndView:
View name = null
View = null
Model = nullFlashMap:
Attributes = nullMockHttpServletResponse:
Status = 200
Error message = null
Headers = [Content-Type:"application/json;charset=UTF-8", Content-Length:"14"]
Content type = application/json;charset=UTF-8
Body = hello XiaoYeQu
Forwarded URL = null
Redirected URL = null
Cookies = []
-------------------------------------------------------------------------------------------------
Service 层的单元测试
创建实体类
创建一个实体类用于测试
import lombok.Data;
@Data
public class User {
private String name;
private int age;
}
创建服务类
用 @Service 来标注服务类,并实例化了一个 User 对象
import com.jia.pojo.User;
import org.springframework.stereotype.Service;
@Service
public class UserService {
public User getUserInfo() {
User user = new User();
user.setName("XiaoYeQu");
user.setAge(18);
return user;
}
}
编写测试
比较实例化的实体 User 和测试的预期值是否一样
import com.jia.pojo.User;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
import static org.hamcrest.CoreMatchers.*;
//表明要在测试环境运行,底层使用的junit测试工具
@RunWith(SpringRunner.class)
// SpringJUnit支持,由此引入Spring-Test框架支持!
//启动整个spring的工程
@SpringBootTest
public class UserServiceTest {
@Autowired
private UserService userService;
@Test
public void getUserInfo() {
User user = userService.getUserInfo();
//比较实际的值和用户预期的值是否一样
System.out.println("------------------------------------------------------------------------------------------");
Assert.assertEquals(18, user.getAge());
Assert.assertEquals(user.getName(), "XiaoYeQu1");
Assert.assertThat(user.getName(), is("XiaoYeQu"));
System.out.println("------------------------------------------------------------------------------------------");
}
}
期望值和实际值不一样时: